File size: 6,021 Bytes
a57534c
 
 
 
2614c61
 
68ebb5b
2614c61
 
 
6176524
 
17ace0e
 
 
 
 
6176524
68ebb5b
6176524
 
 
 
 
 
 
 
8b27c3c
6176524
68ebb5b
b336ffe
 
 
 
 
 
 
 
68ebb5b
 
a57534c
1a81b66
a57534c
fe24735
 
 
a57534c
25e4ae6
a57534c
6176524
a57534c
6176524
8fddb11
6176524
 
 
 
25e4ae6
6176524
 
 
 
022be5b
a57534c
5ef57e6
6176524
8fe1e81
6176524
 
 
 
8fddb11
6176524
 
 
5ef57e6
6176524
8fddb11
6176524
a57534c
6176524
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
25e4ae6
4d64e4d
6176524
e1faf46
6176524
b336ffe
e1faf46
ff52d50
 
 
 
 
 
 
6176524
ff52d50
 
6176524
022be5b
a57534c
6176524
 
 
 
 
 
022be5b
6176524
 
 
 
 
 
8b3fc50
6176524
 
 
 
de02c0f
 
6176524
 
 
 
 
 
 
de02c0f
 
022be5b
68ebb5b
62e0c2b
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
import pandas as pd
import numpy as np
import joblib
import gradio as gr
import os
import tempfile

# Set a custom directory for Gradio's temporary files
os.environ["GRADIO_TEMP"] = tempfile.mkdtemp()

# Dictionary of IoT devices and their corresponding model files
device_models = {
    "Garage Door": "garage_door_model.pkl",
    "GPS Tracker": "gps_tracker_model.pkl",
    "Weather": "weather_model.pkl",
    "Thermostat": "thermostat_model.pkl",
    "Fridge": "fridge_model.pkl"
}

# Define required numeric features for each device
device_features = {
    "Garage Door": ["date_numeric", "time_numeric", "door_state", "sphone_signal", "label"],
    "GPS Tracker": ["date_numeric", "time_numeric", "latitude", "longitude", "label"],
    "Weather": ["date_numeric", "time_numeric", "temperature", "humidity", "label"],
    "Thermostat": ["date_numeric", "time_numeric", "temp_set", "temp_actual", "label"],
    "Fridge": ["date_numeric", "time_numeric", "temp_inside", "door_open", "label"]
}

# Class labels for attack types (assuming same for all devices; adjust if needed)
class_labels = {
    0: "Normal",
    1: "Backdoor",
    2: "DDoS",
    3: "Injection",
    4: "Password Attack",
    5: "Ransomware",
    6: "Scanning",
    7: "XSS",
}

def convert_datetime_features(log_data):
    """Convert date and time into numeric values."""
    try:
        log_data['date'] = pd.to_datetime(log_data['date'], format='%d-%m-%y', errors='coerce')
        log_data['date_numeric'] = log_data['date'].astype(np.int64) // 10**9  

        time_parsed = pd.to_datetime(log_data['time'], format='%H:%M:%S', errors='coerce')
        log_data['time_numeric'] = (time_parsed.dt.hour * 3600) + (time_parsed.dt.minute * 60) + time_parsed.dt.second
    except Exception as e:
        return f"Error processing date/time: {str(e)}", None
    
    return None, log_data

def detect_intrusion(device, file):
    """Process log file and predict attack type based on selected device."""
    # Load the selected device's model
    try:
        model = joblib.load(device_models[device])
    except Exception as e:
        return f"Error loading model for {device}: {str(e)}", None, None

    # Read the uploaded file
    try:
        log_data = pd.read_csv(file.name)
    except Exception as e:
        return f"Error reading file: {str(e)}", None, None

    # Convert date and time features
    error, log_data = convert_datetime_features(log_data)
    if error:
        return error, None, None

    # Get the required features for the selected device
    required_features = device_features[device]
    missing_features = [feature for feature in required_features if feature not in log_data.columns]
    if missing_features:
        return f"Missing features for {device}: {', '.join(missing_features)}", None, None

    # Preprocess device-specific features
    try:
        if device == "Garage Door":
            log_data['door_state'] = log_data['door_state'].astype(str).str.strip().replace({'closed': 0, 'open': 1})
            log_data['sphone_signal'] = pd.to_numeric(log_data['sphone_signal'], errors='coerce')
        elif device == "GPS Tracker":
            log_data['latitude'] = pd.to_numeric(log_data['latitude'], errors='coerce')
            log_data['longitude'] = pd.to_numeric(log_data['longitude'], errors='coerce')
        elif device == "Weather":
            log_data['temperature'] = pd.to_numeric(log_data['temperature'], errors='coerce')
            log_data['humidity'] = pd.to_numeric(log_data['humidity'], errors='coerce')
        elif device == "Thermostat":
            log_data['temp_set'] = pd.to_numeric(log_data['temp_set'], errors='coerce')
            log_data['temp_actual'] = pd.to_numeric(log_data['temp_actual'], errors='coerce')
        elif device == "Fridge":
            log_data['temp_inside'] = pd.to_numeric(log_data['temp_inside'], errors='coerce')
            log_data['door_open'] = log_data['door_open'].astype(str).str.strip().replace({'closed': 0, 'open': 1})

        # Prepare feature values for prediction
        feature_values = log_data[required_features].astype(float).values
        predictions = model.predict(feature_values)
    except Exception as e:
        return f"Error during prediction for {device}: {str(e)}", None, None

    # Map predictions to attack types
    log_data['Prediction'] = [class_labels.get(pred, 'Unknown Attack') for pred in predictions]

    # Format date for output
    log_data['date'] = log_data['date'].dt.strftime('%Y-%m-%d')

    # Select final output columns
    output_df = log_data[['date', 'time', 'Prediction']]

    # Save the output to a CSV file for download
    output_file = f"intrusion_results_{device.lower().replace(' ', '_')}.csv"
    output_df.to_csv(output_file, index=False)

    return None, output_df, output_file

# Create Gradio interface
def gradio_interface(device, file):
    error, df, output_file = detect_intrusion(device, file)
    if error:
        return error, None, None
    return df, df, output_file

iface = gr.Interface(
    fn=gradio_interface,
    inputs=[
        gr.Dropdown(choices=list(device_models.keys()), label="Select IoT Device", value="Garage Door"),
        gr.File(label="Upload Log File (CSV format)")
    ],
    outputs=[
        gr.Textbox(label="Status/Error Message", visible=False),
        gr.Dataframe(label="Intrusion Detection Results"),
        gr.File(label="Download Predictions CSV")
    ],
    title="IoT Intrusion Detection System",
    description=(
        """
        Select an IoT device and upload a CSV log file with the appropriate features for that device.
        Example features per device:
        - Garage Door: date,time,door_state,sphone_signal,label (e.g., 26-04-19,13:59:20,1,-85,normal)
        - GPS Tracker: date,time,latitude,longitude,label
        - Weather: date,time,temperature,humidity,label
        - Thermostat: date,time,temp_set,temp_actual,label
        - Fridge: date,time,temp_inside,door_open,label
        """
    )
)

iface.launch()