├── .gitignore ├── ARCHITECTURE.md ├── CONTRIBUTING.md ├── GETTING_STARTED.md ├── LICENSE ├── README.md ├── Smart IoT Security Framework ├── config.example.json └── requirements.txt /.gitignore: -------------------------------------------------------------------------------- 1 | # Byte-compiled / optimized / DLL files 2 | __pycache__/ 3 | *.py[cod] 4 | *$py.class 5 | 6 | # C extensions 7 | *.so 8 | 9 | # Distribution / packaging 10 | .Python 11 | build/ 12 | develop-eggs/ 13 | dist/ 14 | downloads/ 15 | eggs/ 16 | .eggs/ 17 | lib/ 18 | lib64/ 19 | parts/ 20 | sdist/ 21 | var/ 22 | wheels/ 23 | *.egg-info/ 24 | .installed.cfg 25 | *.egg 26 | MANIFEST 27 | 28 | # PyInstaller 29 | *.manifest 30 | *.spec 31 | 32 | # Installer logs 33 | pip-log.txt 34 | pip-delete-this-directory.txt 35 | 36 | # Unit test / coverage reports 37 | htmlcov/ 38 | .tox/ 39 | .coverage 40 | .coverage.* 41 | .cache 42 | nosetests.xml 43 | coverage.xml 44 | *.cover 45 | .hypothesis/ 46 | .pytest_cache/ 47 | 48 | # Environments 49 | .env 50 | .venv 51 | env/ 52 | venv/ 53 | ENV/ 54 | env.bak/ 55 | venv.bak/ 56 | 57 | # AWS IoT certificates and keys 58 | *.pem 59 | *.key 60 | *.crt 61 | *.cert 62 | 63 | # Configuration files with sensitive info 64 | config.json 65 | 66 | # System-specific files 67 | .DS_Store 68 | .idea/ 69 | .vscode/ 70 | 71 | # Logs 72 | *.log 73 | logs/ 74 | 75 | # Data files 76 | *.csv 77 | *.dat 78 | *.db 79 | -------------------------------------------------------------------------------- /ARCHITECTURE.md: -------------------------------------------------------------------------------- 1 | # Smart IoT Security Framework Architecture 2 | 3 | This document outlines the architecture and design decisions of the Smart IoT Security Framework. 4 | 5 | ## System Overview 6 | 7 | The Smart IoT Security Framework is designed as a hybrid edge-cloud security solution for IoT devices. It uses AI-driven anomaly detection to identify and respond to potential security threats in real-time while maintaining a lightweight footprint suitable for resource-constrained devices. 8 | 9 | ## Architecture Diagram 10 | 11 | ``` 12 | ┌─────────────────────────────────────────────────────────────┐ 13 | │ IoT Device │ 14 | │ │ 15 | │ ┌─────────────────┐ ┌────────────────────────┐ │ 16 | │ │ │ │ │ │ 17 | │ │ Device Software ├────────┤ IoT Security Monitor │ │ 18 | │ │ │ │ │ │ 19 | │ └─────────────────┘ └───────────┬────────────┘ │ 20 | │ │ │ 21 | └─────────────────────────────────────────┼──────────────────┘ 22 | │ 23 | ┌─────────────────────┐ │ ┌──────────────────┐ 24 | │ │ │ │ │ 25 | │ Local MQTT Broker │◄┼─┤ Other IoT │ 26 | │ │ │ │ Devices │ 27 | └─────────────────────┘ │ │ │ 28 | │ └──────────────────┘ 29 | ▼ 30 | ┌─────────────────────────────────────────────────────────────┐ 31 | │ │ 32 | │ AWS IoT Core │ 33 | │ │ 34 | └───────────┬─────────────────────────────────────┬───────────┘ 35 | │ │ 36 | ┌───────────▼───────────────┐ ┌─────────────▼───────────┐ 37 | │ │ │ │ 38 | │ AWS Lambda │ │ Amazon CloudWatch │ 39 | │ (Security Response) │ │ (Monitoring & Alerts) │ 40 | │ │ │ │ 41 | └───────────────────────────┘ └─────────────────────────┘ 42 | ``` 43 | 44 | ## Key Components 45 | 46 | ### 1. IoT Security Monitor 47 | 48 | The core component that runs on the IoT device itself. 49 | 50 | **Responsibilities:** 51 | - Local anomaly detection using the Isolation Forest algorithm 52 | - Command and telemetry validation 53 | - Security policy enforcement 54 | - Communication with AWS IoT Core 55 | - Local event logging 56 | 57 | **Design Considerations:** 58 | - Minimal memory and CPU footprint 59 | - Efficient use of device resources 60 | - Graceful degradation when cloud connectivity is lost 61 | 62 | ### 2. Local MQTT Broker 63 | 64 | Enables local communication between devices in the same network. 65 | 66 | **Responsibilities:** 67 | - Local message routing 68 | - Communication redundancy when cloud connectivity is lost 69 | - Reduced latency for time-sensitive security operations 70 | 71 | ### 3. AWS IoT Core Integration 72 | 73 | Cloud component for centralized management and monitoring. 74 | 75 | **Responsibilities:** 76 | - Secure device authentication and authorization 77 | - Collection of security events and anomalies 78 | - Distribution of security policy updates 79 | - Fleet-wide monitoring and management 80 | 81 | ### 4. Anomaly Detection System 82 | 83 | The AI-driven security mechanism. 84 | 85 | **Responsibilities:** 86 | - Learn normal behavior patterns for each device 87 | - Detect deviations from established patterns 88 | - Adapt to changing device usage over time 89 | - Distinguish between benign anomalies and security threats 90 | 91 | **Implementation Details:** 92 | - Uses Isolation Forest algorithm for unsupervised anomaly detection 93 | - Features extracted from device commands and telemetry 94 | - Model training occurs both locally and in the cloud 95 | - Anomaly thresholds are adjustable based on security requirements 96 | 97 | ## Data Flow 98 | 99 | 1. **Command Processing Flow:** 100 | - Command received via MQTT (local or AWS) 101 | - Features extracted for anomaly detection 102 | - Command analyzed by anomaly detection model 103 | - If normal: command executed 104 | - If anomalous: command blocked, alert generated 105 | 106 | 2. **Telemetry Processing Flow:** 107 | - Device generates telemetry data 108 | - Data analyzed locally for anomalies 109 | - Normal data sent to AWS IoT Core 110 | - Anomalous data triggers security response 111 | 112 | 3. **Security Policy Updates:** 113 | - New policies created in AWS IoT Core 114 | - Policies distributed to devices via MQTT 115 | - Devices update local security configurations 116 | - Acknowledgment sent back to AWS 117 | 118 | ## Security Mechanisms 119 | 120 | ### Authentication & Authorization 121 | - X.509 certificate-based device authentication 122 | - AWS IoT policies for fine-grained access control 123 | - Local credential verification 124 | 125 | ### Communication Security 126 | - TLS 1.2+ for all AWS IoT communications 127 | - Local MQTT security options (TLS, authentication) 128 | - Message signing and verification 129 | 130 | ### Anomaly Detection 131 | - Behavioral analysis using machine learning 132 | - Feature extraction from commands and telemetry 133 | - Adjustable detection sensitivity 134 | 135 | ### Response Mechanisms 136 | - Command blocking 137 | - IP blacklisting 138 | - Alert generation 139 | - Automatic isolation 140 | 141 | ## Scalability Considerations 142 | 143 | The architecture is designed to scale from individual devices to large IoT deployments: 144 | 145 | - Independent operation on each device allows horizontal scaling 146 | - AWS IoT Core provides scalable cloud infrastructure 147 | - Local processing reduces cloud bandwidth requirements 148 | - Flexible deployment options for different device capabilities 149 | 150 | ## Future Enhancements 151 | 152 | - Federated learning for improved anomaly detection 153 | - Device-to-device security communication 154 | - Enhanced behavioral fingerprinting 155 | - Integration with additional cloud security services 156 | - Support for more constrained devices (MQTT-SN, CoAP) 157 | -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # Contributing to Smart IoT Security Framework 2 | 3 | Thank you for your interest in contributing to the Smart IoT Security Framework! This document provides guidelines and instructions for contributing. 4 | 5 | ## Code of Conduct 6 | 7 | By participating in this project, you agree to maintain a respectful and inclusive environment for everyone. 8 | 9 | ## How Can I Contribute? 10 | 11 | ### Reporting Bugs 12 | 13 | - Check the issue tracker to see if the bug has already been reported 14 | - Use the bug report template when creating a new issue 15 | - Include detailed steps to reproduce the bug 16 | - Provide information about your environment (OS, Python version, etc.) 17 | 18 | ### Suggesting Enhancements 19 | 20 | - Check existing enhancement suggestions before creating a new one 21 | - Provide a clear description of the enhancement 22 | - Explain why this enhancement would be useful to most users 23 | 24 | ### Pull Requests 25 | 26 | 1. Fork the repository 27 | 2. Create a new branch for your feature or bugfix 28 | 3. Make your changes 29 | 4. Add or update tests as necessary 30 | 5. Make sure all tests pass 31 | 6. Submit a pull request 32 | 33 | ## Development Setup 34 | 35 | 1. Clone your fork of the repository 36 | 2. Install dependencies: 37 | ```bash 38 | pip install -r requirements.txt 39 | pip install -r requirements-dev.txt 40 | ``` 41 | 3. Set up pre-commit hooks: 42 | ```bash 43 | pre-commit install 44 | ``` 45 | 46 | ## Coding Guidelines 47 | 48 | - Follow PEP 8 style guidelines 49 | - Write docstrings for all functions, classes, and methods 50 | - Add type hints where appropriate 51 | - Keep functions small and focused on a single responsibility 52 | - Write unit tests for new functionality 53 | 54 | ## Testing 55 | 56 | - Run the test suite before submitting a pull request: 57 | ```bash 58 | pytest 59 | ``` 60 | - Aim for high test coverage for new code 61 | 62 | ## Documentation 63 | 64 | - Update documentation for any changes to the API or functionality 65 | - Keep the README up to date 66 | - Add examples for new features 67 | 68 | ## Security Considerations 69 | 70 | - Be cautious when handling security-related code 71 | - Never commit sensitive information (API keys, credentials, etc.) 72 | - Report security vulnerabilities directly to the maintainers rather than opening public issues 73 | 74 | ## Commit Messages 75 | 76 | - Use clear and descriptive commit messages 77 | - Structure commit messages as follows: 78 | ``` 79 | Short summary (limit 50 chars) 80 | 81 | More detailed explanatory text, if necessary. Wrap it to about 72 82 | characters. The blank line separating the summary from the body is 83 | critical. 84 | ``` 85 | 86 | ## Pull Request Process 87 | 88 | 1. Update the README.md with details of changes if applicable 89 | 2. Update the documentation if necessary 90 | 3. The PR should work on the main supported Python versions 91 | 4. Your PR needs approval from at least one maintainer before merging 92 | 93 | ## Questions? 94 | 95 | If you have any questions about contributing, please open an issue labeled 'question'. 96 | 97 | Thank you for your contributions! 98 | -------------------------------------------------------------------------------- /GETTING_STARTED.md: -------------------------------------------------------------------------------- 1 | # Getting Started with Smart IoT Security Framework 2 | 3 | This guide will help you set up and deploy the Smart IoT Security Framework on your IoT devices. 4 | 5 | ## Prerequisites 6 | 7 | Before you begin, ensure you have the following: 8 | 9 | 1. **AWS Account** with access to AWS IoT Core 10 | 2. **Python 3.7+** installed on your development machine and target IoT devices 11 | 3. **MQTT Broker** (like Mosquitto) for local communication (optional but recommended) 12 | 4. **IoT Device** capable of running Python (Raspberry Pi, ESP32, etc.) 13 | 14 | ## Step 1: Set Up AWS IoT Core 15 | 16 | 1. **Create a Thing** in AWS IoT Core: 17 | ``` 18 | AWS Console → IoT Core → Manage → Things → Create things 19 | ``` 20 | 21 | 2. **Generate Certificates**: 22 | - During thing creation, choose to generate certificates 23 | - Download the certificate, private key, and root CA certificate 24 | - Activate the certificate 25 | 26 | 3. **Create a Policy** and attach it to your certificate: 27 | ```json 28 | { 29 | "Version": "2012-10-17", 30 | "Statement": [ 31 | { 32 | "Effect": "Allow", 33 | "Action": "iot:Connect", 34 | "Resource": "arn:aws:iot:your-region:your-account-id:client/${iot:Connection.Thing.ThingName}" 35 | }, 36 | { 37 | "Effect": "Allow", 38 | "Action": "iot:Subscribe", 39 | "Resource": "arn:aws:iot:your-region:your-account-id:topicfilter/devices/${iot:Connection.Thing.ThingName}/*" 40 | }, 41 | { 42 | "Effect": "Allow", 43 | "Action": "iot:Receive", 44 | "Resource": "arn:aws:iot:your-region:your-account-id:topic/devices/${iot:Connection.Thing.ThingName}/*" 45 | }, 46 | { 47 | "Effect": "Allow", 48 | "Action": "iot:Publish", 49 | "Resource": "arn:aws:iot:your-region:your-account-id:topic/devices/${iot:Connection.Thing.ThingName}/*" 50 | } 51 | ] 52 | } 53 | ``` 54 | 55 | ## Step 2: Install the Framework 56 | 57 | 1. **Clone the repository**: 58 | ```bash 59 | git clone https://github.com/yourusername/smart-iot-security-framework.git 60 | cd smart-iot-security-framework 61 | ``` 62 | 63 | 2. **Install dependencies**: 64 | ```bash 65 | pip install -r requirements.txt 66 | ``` 67 | 68 | 3. **Configure the framework**: 69 | - Copy the example configuration file: 70 | ```bash 71 | cp config.example.json config.json 72 | ``` 73 | - Edit the configuration with your AWS IoT Core details and device information: 74 | ```bash 75 | nano config.json 76 | ``` 77 | - Update the following fields: 78 | - `device_id`: Your device's unique identifier 79 | - `aws.endpoint`: Your AWS IoT Core endpoint 80 | - `aws.cert_path`: Path to your device certificate 81 | - `aws.key_path`: Path to your device private key 82 | - `aws.root_ca_path`: Path to the AWS root CA certificate 83 | 84 | ## Step 3: Deploy to Your IoT Device 85 | 86 | 1. **Transfer files to your device**: 87 | - If using Raspberry Pi or similar: 88 | ```bash 89 | scp -r smart-iot-security-framework pi@your-device-ip:~/ 90 | ``` 91 | 92 | 2. **Set up certificates**: 93 | - Place your AWS IoT certificates in the specified paths 94 | - Ensure proper file permissions: 95 | ```bash 96 | chmod 400 /path/to/private.pem.key 97 | ``` 98 | 99 | 3. **Install local MQTT broker** (if using local communication): 100 | - On Raspberry Pi: 101 | ```bash 102 | sudo apt-get update 103 | sudo apt-get install -y mosquitto mosquitto-clients 104 | sudo systemctl enable mosquitto.service 105 | sudo systemctl start mosquitto.service 106 | ``` 107 | 108 | ## Step 4: Run the Security Monitor 109 | 110 | 1. **Basic run**: 111 | ```bash 112 | cd smart-iot-security-framework 113 | python security_monitor.py 114 | ``` 115 | 116 | 2. **Run as a service** (recommended for production): 117 | - Create a systemd service: 118 | ```bash 119 | sudo nano /etc/systemd/system/iot-security.service 120 | ``` 121 | - Add the following content: 122 | ``` 123 | [Unit] 124 | Description=IoT Security Monitor 125 | After=network.target 126 | 127 | [Service] 128 | Type=simple 129 | User=pi 130 | WorkingDirectory=/home/pi/smart-iot-security-framework 131 | ExecStart=/usr/bin/python3 /home/pi/smart-iot-security-framework/security_monitor.py 132 | Restart=always 133 | RestartSec=10 134 | 135 | [Install] 136 | WantedBy=multi-user.target 137 | ``` 138 | - Enable and start the service: 139 | ```bash 140 | sudo systemctl enable iot-security.service 141 | sudo systemctl start iot-security.service 142 | ``` 143 | 144 | ## Step 5: Verify Operation 145 | 146 | 1. **Check logs**: 147 | ```bash 148 | sudo journalctl -u iot-security.service -f 149 | ``` 150 | 151 | 2. **Verify AWS IoT connection**: 152 | - Go to AWS IoT Core → Monitor → MQTT test client 153 | - Subscribe to `devices/your-device-id/status` 154 | - You should see status messages from your device 155 | 156 | 3. **Testing anomaly detection**: 157 | - The system needs some time to learn normal behavior patterns 158 | - Initially, it will operate in learning mode 159 | - After collecting enough data (typically a few hours of operation), it will start detecting anomalies 160 | 161 | ## Step 6: Integration with Your IoT Application 162 | 163 | To integrate the security framework with your existing IoT application: 164 | 165 | 1. **Import the security monitor**: 166 | ```python 167 | from iot_security import IoTSecurityMonitor 168 | ``` 169 | 170 | 2. **Initialize and connect**: 171 | ```python 172 | security_monitor = IoTSecurityMonitor( 173 | device_id="your-device-id", 174 | aws_endpoint="your-aws-endpoint.amazonaws.com", 175 | cert_path="/path/to/certificate.pem.crt", 176 | key_path="/path/to/private.pem.key", 177 | root_ca_path="/path/to/AmazonRootCA1.pem" 178 | ) 179 | security_monitor.connect() 180 | ``` 181 | 182 | 3. **Add to your main loop**: 183 | ```python 184 | try: 185 | while True: 186 | # Your IoT application code 187 | time.sleep(1) 188 | except KeyboardInterrupt: 189 | security_monitor.disconnect() 190 | ``` 191 | 192 | ## Troubleshooting 193 | 194 | ### AWS Connection Issues 195 | - Verify your AWS IoT Core endpoint 196 | - Check certificate and key permissions 197 | - Ensure your policy allows the necessary MQTT operations 198 | - Test connectivity with the AWS IoT Device SDK test client 199 | 200 | ### Anomaly Detection Issues 201 | - The model needs sufficient data to work effectively 202 | - Adjust the anomaly threshold in the configuration 203 | - Check that feature extraction is appropriate for your device 204 | 205 | ### Local MQTT Issues 206 | - Verify the MQTT broker is running: `systemctl status mosquitto` 207 | - Test MQTT connectivity: `mosquitto_sub -t "test/topic"` 208 | - Check firewall settings if using multiple devices 209 | 210 | ## Next Steps 211 | 212 | - Set up CloudWatch alerts for security events 213 | - Configure automated responses to security incidents 214 | - Integrate with your existing monitoring infrastructure 215 | - Customize the anomaly detection for your specific device behavior 216 | 217 | For more advanced configurations and features, see the [ADVANCED_CONFIGURATION.md](ADVANCED_CONFIGURATION.md) document. 218 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | Copyright (c) 2025 3 | Permission is hereby granted, free of charge, to any person obtaining a copy 4 | of this software and associated documentation files (the "Software"), to deal 5 | in the Software without restriction, including without limitation the rights 6 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 7 | copies of the Software, and to permit persons to whom the Software is 8 | furnished to do so, subject to the following conditions: 9 | The above copyright notice and this permission notice shall be included in all 10 | copies or substantial portions of the Software. 11 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 12 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 13 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 14 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 15 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 16 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 17 | SOFTWARE. 18 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Smart IoT Security Framework 2 | 3 | A lightweight security protocol for IoT devices using AI-driven anomaly detection to prevent unauthorized access. This framework leverages Edge AI, Python, MQTT, and AWS IoT Core to provide robust security for resource-constrained IoT devices. 4 | 5 | ![Smart IoT Security Framework](https://via.placeholder.com/800x400?text=Smart+IoT+Security+Framework) 6 | 7 | ## Features 8 | 9 | - **AI-Driven Anomaly Detection**: Automatically detects unusual patterns and potential security threats 10 | - **Edge Computing Security**: Processes security decisions locally to minimize latency and cloud dependence 11 | - **AWS IoT Core Integration**: Seamless connection with AWS cloud services for monitoring and management 12 | - **Lightweight Design**: Optimized for resource-constrained IoT devices 13 | - **Flexible Deployment**: Adaptable to various IoT device types and use cases 14 | - **Real-time Threat Response**: Immediate isolation and mitigation of detected security threats 15 | 16 | ## Architecture 17 | 18 | The Smart IoT Security Framework utilizes a hybrid architecture combining edge and cloud components: 19 | 20 | 1. **Edge Component**: 21 | - Runs directly on IoT devices 22 | - Performs real-time anomaly detection using Isolation Forest algorithm 23 | - Processes security decisions locally to reduce latency 24 | - Maintains local MQTT communication 25 | 26 | 2. **Cloud Component**: 27 | - Integrates with AWS IoT Core 28 | - Provides centralized monitoring and management 29 | - Enables security policy updates across device fleet 30 | - Stores long-term security analytics 31 | 32 | ## Installation 33 | 34 | ### Prerequisites 35 | 36 | - Python 3.7+ 37 | - AWS IoT Core account and configured certificates 38 | - Mosquitto or other MQTT broker (for local communication) 39 | - Device capable of running Python (Raspberry Pi, ESP32 with MicroPython, etc.) 40 | 41 | ### Basic Installation 42 | 43 | ```bash 44 | # Clone the repository 45 | git clone https://github.com/yourusername/smart-iot-security-framework.git 46 | cd smart-iot-security-framework 47 | 48 | # Install dependencies 49 | pip install -r requirements.txt 50 | 51 | # Configure your device (edit config.json with your settings) 52 | cp config.example.json config.json 53 | nano config.json 54 | ``` 55 | 56 | ## Quick Start 57 | 58 | 1. Configure your AWS IoT Core endpoint and certificates 59 | 2. Update the device ID and other parameters in `config.json` 60 | 3. Run the security monitor: 61 | 62 | ```bash 63 | python security_monitor.py 64 | ``` 65 | 66 | ## Example Usage 67 | 68 | ```python 69 | from iot_security import IoTSecurityMonitor 70 | 71 | # Initialize security monitor 72 | security_monitor = IoTSecurityMonitor( 73 | device_id="iot-sensor-001", 74 | aws_endpoint="your-aws-iot-endpoint.amazonaws.com", 75 | cert_path="/path/to/certificate.pem.crt", 76 | key_path="/path/to/private.pem.key", 77 | root_ca_path="/path/to/AmazonRootCA1.pem" 78 | ) 79 | 80 | # Connect to AWS IoT Core and local MQTT 81 | security_monitor.connect() 82 | 83 | # Update security policy 84 | security_monitor.update_security_policy({ 85 | "blocked_ips": ["192.168.1.100"], 86 | "anomaly_threshold": 0.75 87 | }) 88 | 89 | # Run in your main loop 90 | try: 91 | while True: 92 | # Your device's main functionality here 93 | time.sleep(10) 94 | except KeyboardInterrupt: 95 | security_monitor.disconnect() 96 | ``` 97 | 98 | ## Configuration Options 99 | 100 | | Parameter | Description | Default | 101 | |-----------|-------------|---------| 102 | | `device_id` | Unique identifier for the IoT device | None (Required) | 103 | | `aws_endpoint` | AWS IoT Core endpoint | None (Required) | 104 | | `cert_path` | Path to device certificate | None (Required) | 105 | | `key_path` | Path to private key | None (Required) | 106 | | `root_ca_path` | Path to root CA certificate | None (Required) | 107 | | `client_id` | MQTT client ID | Random UUID | 108 | | `anomaly_threshold` | Threshold for anomaly detection (0-1) | 0.85 | 109 | | `history_size` | Size of behavior history buffer | 100 | 110 | 111 | ## Contributing 112 | 113 | Contributions are welcome! Please feel free to submit a Pull Request. 114 | 115 | 1. Fork the repository 116 | 2. Create your feature branch (`git checkout -b feature/amazing-feature`) 117 | 3. Commit your changes (`git commit -m 'Add some amazing feature'`) 118 | 4. Push to the branch (`git push origin feature/amazing-feature`) 119 | 5. Open a Pull Request 120 | 121 | ## License 122 | 123 | This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details. 124 | 125 | ## Acknowledgments 126 | 127 | - AWS IoT Core for cloud connectivity 128 | - Scikit-learn for the Isolation Forest implementation 129 | - Paho MQTT for MQTT client functionality 130 | -------------------------------------------------------------------------------- /Smart IoT Security Framework: -------------------------------------------------------------------------------- 1 | # Smart IoT Security Framework 2 | # A lightweight security protocol for IoT devices using AI-driven anomaly detection 3 | 4 | import json 5 | import time 6 | import uuid 7 | import numpy as np 8 | import paho.mqtt.client as mqtt 9 | from datetime import datetime 10 | from awscrt import mqtt as aws_mqtt 11 | from awsiot import mqtt_connection_builder 12 | from sklearn.ensemble import IsolationForest 13 | from collections import deque 14 | 15 | class IoTSecurityMonitor: 16 | def __init__(self, device_id, aws_endpoint, cert_path, key_path, root_ca_path, 17 | client_id=None, anomaly_threshold=0.85, history_size=100): 18 | """ 19 | Initialize the IoT Security Monitor. 20 | 21 | Args: 22 | device_id (str): Unique identifier for the IoT device 23 | aws_endpoint (str): AWS IoT Core endpoint 24 | cert_path (str): Path to device certificate 25 | key_path (str): Path to private key 26 | root_ca_path (str): Path to root CA certificate 27 | client_id (str, optional): MQTT client ID. Defaults to a UUID. 28 | anomaly_threshold (float, optional): Threshold for anomaly detection. Defaults to 0.85. 29 | history_size (int, optional): Size of the history buffer for behavior analysis. Defaults to 100. 30 | """ 31 | self.device_id = device_id 32 | self.client_id = client_id or f"iot-device-{uuid.uuid4()}" 33 | self.anomaly_threshold = anomaly_threshold 34 | 35 | # Initialize connection to AWS IoT Core 36 | self.aws_endpoint = aws_endpoint 37 | self.cert_path = cert_path 38 | self.key_path = key_path 39 | self.root_ca_path = root_ca_path 40 | self.aws_connection = self._setup_aws_connection() 41 | 42 | # Local MQTT broker for edge processing 43 | self.local_mqtt_client = mqtt.Client() 44 | self.local_mqtt_client.on_connect = self._on_local_connect 45 | self.local_mqtt_client.on_message = self._on_local_message 46 | 47 | # Anomaly detection model 48 | self.model = IsolationForest(contamination=0.05, random_state=42) 49 | self.is_model_trained = False 50 | 51 | # Device behavior history 52 | self.behavior_history = deque(maxlen=history_size) 53 | 54 | # Security state 55 | self.security_state = { 56 | "status": "normal", 57 | "last_anomaly": None, 58 | "blocked_ips": set(), 59 | "auth_failures": {}, 60 | "access_log": deque(maxlen=100) 61 | } 62 | 63 | # Topics 64 | self.anomaly_topic = f"devices/{self.device_id}/security/anomalies" 65 | self.telemetry_topic = f"devices/{self.device_id}/telemetry" 66 | self.command_topic = f"devices/{self.device_id}/commands" 67 | self.status_topic = f"devices/{self.device_id}/status" 68 | 69 | def _setup_aws_connection(self): 70 | """Set up the AWS IoT Core MQTT connection.""" 71 | return mqtt_connection_builder.mtls_from_path( 72 | endpoint=self.aws_endpoint, 73 | cert_filepath=self.cert_path, 74 | pri_key_filepath=self.key_path, 75 | ca_filepath=self.root_ca_path, 76 | client_id=self.client_id, 77 | clean_session=True, 78 | keep_alive_secs=30 79 | ) 80 | 81 | def _on_local_connect(self, client, userdata, flags, rc): 82 | """Callback for when the local MQTT client connects.""" 83 | print(f"Connected to local MQTT broker with result code: {rc}") 84 | client.subscribe(f"local/{self.device_id}/#") 85 | 86 | def _on_local_message(self, client, userdata, msg): 87 | """Callback for when a message is received on the local MQTT broker.""" 88 | try: 89 | payload = json.loads(msg.payload.decode()) 90 | topic = msg.topic 91 | 92 | # Process local messages for security analysis 93 | if "command" in topic: 94 | self._analyze_command(payload, is_local=True) 95 | elif "data" in topic: 96 | self._analyze_telemetry(payload, is_local=True) 97 | except Exception as e: 98 | self._log_security_event("error", f"Error processing local message: {str(e)}") 99 | 100 | def connect(self): 101 | """Connect to both AWS IoT Core and local MQTT broker.""" 102 | # Connect to AWS IoT Core 103 | connect_future = self.aws_connection.connect() 104 | connect_future.result() 105 | print(f"Connected to AWS IoT Core as {self.client_id}") 106 | 107 | # Subscribe to AWS topics 108 | self.aws_connection.subscribe( 109 | topic=self.command_topic, 110 | qos=aws_mqtt.QoS.AT_LEAST_ONCE, 111 | callback=self._handle_aws_command 112 | ) 113 | 114 | # Connect to local MQTT broker 115 | try: 116 | self.local_mqtt_client.connect("localhost", 1883, 60) 117 | self.local_mqtt_client.loop_start() 118 | except Exception as e: 119 | print(f"Error connecting to local MQTT broker: {str(e)}") 120 | 121 | # Publish initial status 122 | self._publish_status() 123 | 124 | def _handle_aws_command(self, topic, payload, **kwargs): 125 | """Handle commands received from AWS IoT Core.""" 126 | try: 127 | message = json.loads(payload.decode()) 128 | source_ip = message.get("source_ip", "unknown") 129 | command = message.get("command") 130 | 131 | # Log the command 132 | self._log_security_event("command", f"Received command {command} from {source_ip}") 133 | 134 | # Analyze the command for security anomalies 135 | anomaly_detected = self._analyze_command(message) 136 | 137 | if anomaly_detected: 138 | # If anomaly detected, don't execute the command 139 | self._publish_anomaly(command, source_ip, "Suspicious command pattern detected") 140 | return 141 | 142 | # Execute the validated command 143 | self._execute_command(command, message) 144 | 145 | except Exception as e: 146 | self._log_security_event("error", f"Error handling command: {str(e)}") 147 | 148 | def _analyze_command(self, message, is_local=False): 149 | """ 150 | Analyze a command for security anomalies. 151 | 152 | Returns: 153 | bool: True if anomaly detected, False otherwise 154 | """ 155 | command = message.get("command") 156 | source = message.get("source_ip", "local" if is_local else "unknown") 157 | timestamp = message.get("timestamp", time.time()) 158 | 159 | # Check if source is blocked 160 | if source in self.security_state["blocked_ips"]: 161 | self._log_security_event("blocked", f"Blocked command from blacklisted source: {source}") 162 | return True 163 | 164 | # Feature extraction for anomaly detection 165 | features = self._extract_command_features(command, source, timestamp) 166 | 167 | # Add to behavior history 168 | self.behavior_history.append(features) 169 | 170 | # Train model if we have enough data and it's not yet trained 171 | if len(self.behavior_history) >= 50 and not self.is_model_trained: 172 | self._train_model() 173 | 174 | # Detect anomalies if model is trained 175 | if self.is_model_trained: 176 | is_anomaly = self._detect_anomaly(features) 177 | if is_anomaly: 178 | self._log_security_event("anomaly", f"Command anomaly detected from {source}: {command}") 179 | return True 180 | 181 | return False 182 | 183 | def _extract_command_features(self, command, source, timestamp): 184 | """Extract features from a command for anomaly detection.""" 185 | # This is a simplified feature extraction - in production, this would be more sophisticated 186 | hour_of_day = datetime.fromtimestamp(timestamp).hour 187 | 188 | # Simple features for demonstration 189 | features = [ 190 | hour_of_day / 24.0, # Normalize hour of day 191 | 1.0 if "set" in command else 0.0, 192 | 1.0 if "get" in command else 0.0, 193 | 1.0 if "restart" in command else 0.0, 194 | 1.0 if "update" in command else 0.0, 195 | 1.0 if source == "local" else 0.0 196 | ] 197 | return features 198 | 199 | def _train_model(self): 200 | """Train the anomaly detection model on collected behavior history.""" 201 | print("Training anomaly detection model...") 202 | X = np.array(list(self.behavior_history)) 203 | self.model.fit(X) 204 | self.is_model_trained = True 205 | print("Anomaly detection model trained successfully") 206 | 207 | def _detect_anomaly(self, features): 208 | """ 209 | Detect if a set of features represents an anomaly. 210 | 211 | Returns: 212 | bool: True if anomaly detected, False otherwise 213 | """ 214 | features_array = np.array([features]) 215 | scores = self.model.decision_function(features_array) 216 | # Higher score means less anomalous 217 | return scores[0] < -self.anomaly_threshold 218 | 219 | def _analyze_telemetry(self, data, is_local=False): 220 | """Analyze telemetry data for security anomalies.""" 221 | # Similar to command analysis but for telemetry data 222 | # Implementation would depend on the specific telemetry data structure 223 | pass 224 | 225 | def _execute_command(self, command, message): 226 | """Execute a validated command.""" 227 | # This would contain the logic to execute different commands 228 | print(f"Executing command: {command}") 229 | 230 | # Update status after command execution 231 | self._publish_status() 232 | 233 | def _publish_anomaly(self, command, source, reason): 234 | """Publish an anomaly event to AWS IoT Core.""" 235 | anomaly_data = { 236 | "device_id": self.device_id, 237 | "timestamp": time.time(), 238 | "command": command, 239 | "source": source, 240 | "reason": reason 241 | } 242 | 243 | # Update security state 244 | self.security_state["status"] = "alert" 245 | self.security_state["last_anomaly"] = anomaly_data 246 | 247 | # Publish to AWS IoT Core 248 | self.aws_connection.publish( 249 | topic=self.anomaly_topic, 250 | payload=json.dumps(anomaly_data), 251 | qos=aws_mqtt.QoS.AT_LEAST_ONCE 252 | ) 253 | 254 | # Log locally 255 | self._log_security_event("alert", f"Published anomaly alert: {reason}") 256 | 257 | def _publish_status(self): 258 | """Publish current device status to AWS IoT Core.""" 259 | status_data = { 260 | "device_id": self.device_id, 261 | "timestamp": time.time(), 262 | "security_status": self.security_state["status"], 263 | "model_trained": self.is_model_trained 264 | } 265 | 266 | self.aws_connection.publish( 267 | topic=self.status_topic, 268 | payload=json.dumps(status_data), 269 | qos=aws_mqtt.QoS.AT_LEAST_ONCE 270 | ) 271 | 272 | def _log_security_event(self, event_type, message): 273 | """Log a security event locally.""" 274 | event = { 275 | "timestamp": time.time(), 276 | "type": event_type, 277 | "message": message 278 | } 279 | self.security_state["access_log"].append(event) 280 | print(f"SECURITY EVENT [{event_type}]: {message}") 281 | 282 | def update_security_policy(self, policy_update): 283 | """Update the security policy based on external input.""" 284 | if "blocked_ips" in policy_update: 285 | for ip in policy_update["blocked_ips"]: 286 | self.security_state["blocked_ips"].add(ip) 287 | 288 | if "anomaly_threshold" in policy_update: 289 | self.anomaly_threshold = policy_update["anomaly_threshold"] 290 | 291 | self._log_security_event("policy", "Security policy updated") 292 | 293 | def disconnect(self): 294 | """Disconnect from AWS IoT Core and local MQTT broker.""" 295 | # Disconnect from AWS IoT Core 296 | disconnect_future = self.aws_connection.disconnect() 297 | disconnect_future.result() 298 | 299 | # Disconnect from local MQTT broker 300 | self.local_mqtt_client.loop_stop() 301 | self.local_mqtt_client.disconnect() 302 | 303 | print(f"Disconnected {self.client_id} from all services") 304 | 305 | 306 | # Example deployment script 307 | def deploy_security_framework(): 308 | """Deploy the IoT Security Framework to a device.""" 309 | 310 | # Configuration 311 | config = { 312 | "device_id": "iot-sensor-001", 313 | "aws_endpoint": "your-aws-iot-endpoint.amazonaws.com", 314 | "cert_path": "/path/to/certificate.pem.crt", 315 | "key_path": "/path/to/private.pem.key", 316 | "root_ca_path": "/path/to/AmazonRootCA1.pem", 317 | "anomaly_threshold": 0.8 318 | } 319 | 320 | # Initialize security monitor 321 | security_monitor = IoTSecurityMonitor( 322 | device_id=config["device_id"], 323 | aws_endpoint=config["aws_endpoint"], 324 | cert_path=config["cert_path"], 325 | key_path=config["key_path"], 326 | root_ca_path=config["root_ca_path"], 327 | anomaly_threshold=config["anomaly_threshold"] 328 | ) 329 | 330 | try: 331 | # Connect to AWS IoT Core and local MQTT 332 | security_monitor.connect() 333 | 334 | # Main processing loop 335 | while True: 336 | # This would process local data, update models, etc. 337 | time.sleep(10) 338 | 339 | except KeyboardInterrupt: 340 | print("Shutting down security monitor...") 341 | finally: 342 | security_monitor.disconnect() 343 | 344 | 345 | if __name__ == "__main__": 346 | deploy_security_framework() 347 | -------------------------------------------------------------------------------- /config.example.json: -------------------------------------------------------------------------------- 1 | { 2 | "device": { 3 | "device_id": "iot-sensor-001", 4 | "device_type": "environmental-sensor", 5 | "location": "building-a-room-101" 6 | }, 7 | "aws": { 8 | "endpoint": "your-aws-iot-endpoint.amazonaws.com", 9 | "cert_path": "/path/to/certificate.pem.crt", 10 | "key_path": "/path/to/private.pem.key", 11 | "root_ca_path": "/path/to/AmazonRootCA1.pem", 12 | "client_id": "" 13 | }, 14 | "mqtt": { 15 | "local_broker": "localhost", 16 | "local_port": 1883, 17 | "use_local": true 18 | }, 19 | "security": { 20 | "anomaly_threshold": 0.85, 21 | "history_size": 100, 22 | "blocked_ips": [], 23 | "training_mode": false, 24 | "log_level": "INFO" 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | numpy>=1.20.0 2 | paho-mqtt>=1.6.1 3 | scikit-learn>=1.0.2 4 | awsiotsdk>=1.11.0 5 | boto3>=1.24.0 6 | matplotlib>=3.5.0 7 | --------------------------------------------------------------------------------