Spaces:
Sleeping
Sleeping
File size: 4,999 Bytes
2d1fbd9 ea4398d 2d1fbd9 ea4398d 2d1fbd9 ea4398d 2d1fbd9 ea4398d 2d1fbd9 bfd5a34 2d1fbd9 bfd5a34 ea4398d 2d1fbd9 ea4398d 2d1fbd9 bfd5a34 2d1fbd9 ea4398d 2d1fbd9 ea4398d 2d1fbd9 ea4398d 2d1fbd9 ea4398d | 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 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 | import streamlit as st
import torch
import torch.nn as nn
import numpy as np
import pandas as pd
import joblib
import plotly.graph_objects as go
# -----------------------------
# Page config
# -----------------------------
st.set_page_config(
page_title="Cyber Threat Detection Dashboard",
page_icon="🛡️",
layout="wide"
)
# -----------------------------
# Feature names (MUST match training order)
# -----------------------------
FEATURE_COLUMNS = [
"processId",
"threadId",
"parentProcessId",
"userId",
"mountNamespace",
"argsNum",
"returnValue"
]
# -----------------------------
# Title
# -----------------------------
st.markdown("""
# 🛡️ Cyber Threat Detection Dashboard
**SOC-Style Deep Learning–Based Suspicious Activity Detection**
""")
st.markdown("---")
# -----------------------------
# Load scaler
# -----------------------------
scaler = joblib.load("scaler.pkl")
INPUT_DIM = len(FEATURE_COLUMNS)
# -----------------------------
# Model (EXACT training architecture)
# -----------------------------
model = nn.Sequential(
nn.Linear(INPUT_DIM, 128),
nn.BatchNorm1d(128),
nn.ReLU(),
nn.Dropout(0.3),
nn.Linear(128, 64),
nn.BatchNorm1d(64),
nn.ReLU(),
nn.Dropout(0.3),
nn.Linear(64, 1)
)
model.load_state_dict(torch.load("model.pth", map_location="cpu"))
model.eval()
# =============================
# SIDEBAR
# =============================
st.sidebar.header("🔍 Analysis Mode")
mode = st.sidebar.radio(
"Choose input type",
["Single Log Event", "Upload CSV (Batch Analysis)"]
)
# =============================
# SINGLE EVENT MODE
# =============================
if mode == "Single Log Event":
st.sidebar.subheader("Log Features")
features = []
for col in FEATURE_COLUMNS:
val = st.sidebar.number_input(col, value=0)
features.append(val)
if st.sidebar.button("🚨 Analyze Event"):
x = np.array(features).reshape(1, -1)
x_scaled = scaler.transform(x)
x_tensor = torch.tensor(x_scaled, dtype=torch.float32)
with torch.no_grad():
prob = torch.sigmoid(model(x_tensor)).item()
# Risk logic
if prob > 0.7:
risk = "HIGH"
color = "red"
action = "Immediate investigation required. Isolate affected system."
elif prob > 0.4:
risk = "MEDIUM"
color = "orange"
action = "Monitor closely. Correlate with other logs."
else:
risk = "LOW"
color = "green"
action = "No action required. Log for auditing."
col1, col2, col3 = st.columns(3)
col1.metric("Risk Level", risk)
col2.metric("Suspicion Probability", f"{prob:.2f}")
col3.metric("Recommended Action", action)
fig = go.Figure(go.Indicator(
mode="gauge+number",
value=prob * 100,
title={'text': "Threat Confidence (%)"},
gauge={
'axis': {'range': [0, 100]},
'bar': {'color': color},
'steps': [
{'range': [0, 40], 'color': "lightgreen"},
{'range': [40, 70], 'color': "orange"},
{'range': [70, 100], 'color': "red"}
],
}
))
st.plotly_chart(fig, use_container_width=True)
# =============================
# CSV UPLOAD MODE
# =============================
else:
st.subheader("📄 Batch Log Analysis")
uploaded_file = st.file_uploader(
"Upload CSV file (validation/test logs)",
type=["csv"]
)
if uploaded_file:
df = pd.read_csv(uploaded_file)
# Drop label column if present
if "sus_label" in df.columns:
df = df.drop(columns=["sus_label"])
# Ensure correct columns
missing = set(FEATURE_COLUMNS) - set(df.columns)
if missing:
st.error(f"Missing required columns: {missing}")
else:
df = df[FEATURE_COLUMNS] # enforce correct order
X_scaled = scaler.transform(df.values)
X_tensor = torch.tensor(X_scaled, dtype=torch.float32)
with torch.no_grad():
probs = torch.sigmoid(model(X_tensor)).numpy().flatten()
df["suspicion_probability"] = probs
df["risk_level"] = df["suspicion_probability"].apply(
lambda p: "HIGH" if p > 0.7 else "MEDIUM" if p > 0.4 else "LOW"
)
st.success("Batch analysis completed")
st.dataframe(df, use_container_width=True)
st.markdown("### 📊 Risk Distribution")
st.bar_chart(df["risk_level"].value_counts())
# =============================
# Footer
# =============================
st.markdown("---")
st.info(
"This dashboard simulates a Security Operations Center (SOC) workflow by "
"analyzing system logs using a deep learning model trained on the BETH dataset."
)
|