Update app.py
Browse files
app.py
CHANGED
@@ -1,175 +1,107 @@
|
|
1 |
import dash
|
2 |
from dash import dcc, html
|
3 |
-
from dash.dependencies import Input, Output
|
4 |
import pandas as pd
|
5 |
import numpy as np
|
6 |
from datetime import datetime, timedelta
|
7 |
from sklearn.ensemble import IsolationForest
|
8 |
from sklearn.preprocessing import StandardScaler
|
9 |
import plotly.graph_objs as go
|
10 |
-
from plotly.subplots import make_subplots
|
11 |
-
import warnings
|
12 |
-
warnings.filterwarnings('ignore')
|
13 |
|
14 |
-
|
15 |
-
|
16 |
-
|
17 |
-
self.detect_anomalies()
|
18 |
-
|
19 |
-
def generate_data(self, n_samples=100):
|
20 |
-
current_time = datetime.now()
|
21 |
-
timestamps = [current_time - timedelta(minutes=i) for i in range(n_samples)]
|
22 |
-
|
23 |
-
self.data = pd.DataFrame({
|
24 |
-
'timestamp': timestamps,
|
25 |
-
'network_traffic': np.random.normal(1000, 200, n_samples),
|
26 |
-
'failed_logins': np.random.poisson(5, n_samples),
|
27 |
-
'suspicious_ips': np.random.poisson(2, n_samples),
|
28 |
-
'data_exfiltration': np.random.normal(50, 10, n_samples),
|
29 |
-
'severity': np.random.choice(['Low', 'Medium', 'High'], n_samples),
|
30 |
-
'source_country': np.random.choice(['USA', 'China', 'Russia', 'UK', 'India'], n_samples),
|
31 |
-
'attack_type': np.random.choice(['DDoS', 'Brute Force', 'SQL Injection', 'XSS', 'Malware'], n_samples),
|
32 |
-
'port': np.random.choice([80, 443, 22, 3389, 8080], n_samples)
|
33 |
-
})
|
34 |
-
|
35 |
-
def detect_anomalies(self):
|
36 |
-
isolation_forest = IsolationForest(contamination=0.1, random_state=42)
|
37 |
-
scaler = StandardScaler()
|
38 |
-
|
39 |
-
features = ['network_traffic', 'failed_logins', 'suspicious_ips', 'data_exfiltration']
|
40 |
-
X = self.data[features]
|
41 |
-
X_scaled = scaler.fit_transform(X)
|
42 |
-
|
43 |
-
self.data['is_anomaly'] = isolation_forest.fit_predict(X_scaled) == -1
|
44 |
|
45 |
-
|
46 |
-
|
47 |
-
|
48 |
-
|
49 |
-
x=self.data[~self.data['is_anomaly']]['timestamp'],
|
50 |
-
y=self.data[~self.data['is_anomaly']]['network_traffic'],
|
51 |
-
name='Normal Traffic',
|
52 |
-
mode='lines',
|
53 |
-
line=dict(color='blue')
|
54 |
-
))
|
55 |
-
|
56 |
-
fig.add_trace(go.Scatter(
|
57 |
-
x=self.data[self.data['is_anomaly']]['timestamp'],
|
58 |
-
y=self.data[self.data['is_anomaly']]['network_traffic'],
|
59 |
-
name='Anomalies',
|
60 |
-
mode='markers',
|
61 |
-
marker=dict(color='red', size=10)
|
62 |
-
))
|
63 |
-
|
64 |
-
fig.update_layout(
|
65 |
-
title='Network Traffic with Anomaly Detection',
|
66 |
-
xaxis_title='Time',
|
67 |
-
yaxis_title='Network Traffic (bytes)',
|
68 |
-
template='plotly_white'
|
69 |
-
)
|
70 |
-
return fig
|
71 |
|
72 |
-
|
73 |
-
|
74 |
-
|
75 |
-
|
76 |
-
|
77 |
-
|
78 |
-
|
79 |
-
|
80 |
-
[{'type': 'bar'}, {'type': 'bar'}]]
|
81 |
-
)
|
82 |
-
|
83 |
-
fig.add_trace(
|
84 |
-
go.Scatter(x=self.data['timestamp'], y=self.data['network_traffic'],
|
85 |
-
name='Network Traffic'),
|
86 |
-
row=1, col=1
|
87 |
-
)
|
88 |
-
|
89 |
-
fig.add_trace(
|
90 |
-
go.Bar(x=self.data['timestamp'], y=self.data['failed_logins'],
|
91 |
-
name='Failed Logins'),
|
92 |
-
row=1, col=2
|
93 |
-
)
|
94 |
-
|
95 |
-
attack_counts = self.data['attack_type'].value_counts()
|
96 |
-
fig.add_trace(
|
97 |
-
go.Pie(labels=attack_counts.index, values=attack_counts.values,
|
98 |
-
name='Attack Types'),
|
99 |
-
row=2, col=1
|
100 |
-
)
|
101 |
-
|
102 |
-
country_counts = self.data['source_country'].value_counts()
|
103 |
-
fig.add_trace(
|
104 |
-
go.Pie(labels=country_counts.index, values=country_counts.values,
|
105 |
-
name='Countries'),
|
106 |
-
row=2, col=2
|
107 |
-
)
|
108 |
-
|
109 |
-
port_counts = self.data['port'].value_counts()
|
110 |
-
fig.add_trace(
|
111 |
-
go.Bar(x=port_counts.index, y=port_counts.values,
|
112 |
-
name='Port Activity'),
|
113 |
-
row=3, col=1
|
114 |
-
)
|
115 |
-
|
116 |
-
severity_counts = self.data['severity'].value_counts()
|
117 |
-
fig.add_trace(
|
118 |
-
go.Bar(x=severity_counts.index, y=severity_counts.values,
|
119 |
-
name='Severity',
|
120 |
-
marker_color=['green', 'yellow', 'red']),
|
121 |
-
row=3, col=2
|
122 |
-
)
|
123 |
-
|
124 |
-
fig.update_layout(height=1200, showlegend=False,
|
125 |
-
title_text="Security Overview Dashboard")
|
126 |
-
return fig
|
127 |
|
128 |
-
|
129 |
-
|
130 |
-
|
131 |
-
|
132 |
-
|
133 |
-
|
134 |
-
|
135 |
-
|
136 |
-
|
137 |
-
|
138 |
-
|
139 |
-
return html.Table(
|
140 |
-
[html.Tr([html.Th(key), html.Td(value)]) for key, value in metrics.items()],
|
141 |
-
className='metrics-table'
|
142 |
-
)
|
143 |
|
144 |
-
#
|
145 |
-
|
146 |
-
|
147 |
|
148 |
-
#
|
149 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
150 |
|
151 |
-
# Define the layout
|
152 |
app.layout = html.Div([
|
153 |
html.H1("AI-Enhanced Cybersecurity Dashboard",
|
154 |
style={'textAlign': 'center', 'padding': '20px'}),
|
155 |
|
|
|
156 |
html.Div([
|
157 |
html.H2("Key Metrics", style={'textAlign': 'center'}),
|
158 |
-
|
|
|
|
|
|
|
|
|
|
|
159 |
], style={'padding': '20px'}),
|
160 |
|
|
|
161 |
html.Div([
|
162 |
html.H2("Network Traffic Analysis", style={'textAlign': 'center'}),
|
163 |
-
dcc.Graph(figure=
|
164 |
-
], style={'padding': '20px'}),
|
165 |
-
|
166 |
-
html.Div([
|
167 |
-
html.H2("Security Overview", style={'textAlign': 'center'}),
|
168 |
-
dcc.Graph(figure=security_analytics.plot_security_overview())
|
169 |
], style={'padding': '20px'})
|
170 |
])
|
171 |
|
172 |
-
# Add
|
173 |
app.index_string = '''
|
174 |
<!DOCTYPE html>
|
175 |
<html>
|
@@ -184,17 +116,16 @@ app.index_string = '''
|
|
184 |
margin: 0;
|
185 |
background-color: #f0f2f5;
|
186 |
}
|
187 |
-
|
188 |
width: 100%;
|
189 |
-
|
190 |
-
margin: 20px 0;
|
191 |
}
|
192 |
-
|
193 |
padding: 12px;
|
194 |
text-align: left;
|
195 |
border-bottom: 1px solid #ddd;
|
196 |
}
|
197 |
-
|
198 |
background-color: #f8f9fa;
|
199 |
}
|
200 |
</style>
|
|
|
1 |
import dash
|
2 |
from dash import dcc, html
|
|
|
3 |
import pandas as pd
|
4 |
import numpy as np
|
5 |
from datetime import datetime, timedelta
|
6 |
from sklearn.ensemble import IsolationForest
|
7 |
from sklearn.preprocessing import StandardScaler
|
8 |
import plotly.graph_objs as go
|
|
|
|
|
|
|
9 |
|
10 |
+
# Initialize the Dash app
|
11 |
+
app = dash.Dash(__name__)
|
12 |
+
server = app.server
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
13 |
|
14 |
+
# Generate mock data
|
15 |
+
def generate_mock_data(n_samples=100):
|
16 |
+
current_time = datetime.now()
|
17 |
+
timestamps = [current_time - timedelta(minutes=i) for i in range(n_samples)]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
18 |
|
19 |
+
data = pd.DataFrame({
|
20 |
+
'timestamp': timestamps,
|
21 |
+
'network_traffic': np.random.normal(1000, 200, n_samples),
|
22 |
+
'failed_logins': np.random.poisson(5, n_samples),
|
23 |
+
'suspicious_ips': np.random.poisson(2, n_samples),
|
24 |
+
'data_exfiltration': np.random.normal(50, 10, n_samples)
|
25 |
+
})
|
26 |
+
return data
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
27 |
|
28 |
+
# Detect anomalies
|
29 |
+
def detect_anomalies(df):
|
30 |
+
isolation_forest = IsolationForest(contamination=0.1, random_state=42)
|
31 |
+
scaler = StandardScaler()
|
32 |
+
|
33 |
+
features = ['network_traffic', 'failed_logins', 'suspicious_ips', 'data_exfiltration']
|
34 |
+
X = df[features]
|
35 |
+
X_scaled = scaler.fit_transform(X)
|
36 |
+
|
37 |
+
return isolation_forest.fit_predict(X_scaled) == -1
|
|
|
|
|
|
|
|
|
|
|
38 |
|
39 |
+
# Generate data and detect anomalies
|
40 |
+
df = generate_mock_data()
|
41 |
+
anomalies = detect_anomalies(df)
|
42 |
|
43 |
+
# Create figures
|
44 |
+
def create_network_traffic_figure():
|
45 |
+
fig = go.Figure()
|
46 |
+
|
47 |
+
# Normal traffic
|
48 |
+
fig.add_trace(go.Scatter(
|
49 |
+
x=df[~anomalies]['timestamp'],
|
50 |
+
y=df[~anomalies]['network_traffic'],
|
51 |
+
name='Normal Traffic',
|
52 |
+
mode='lines',
|
53 |
+
line=dict(color='blue')
|
54 |
+
))
|
55 |
+
|
56 |
+
# Anomalies
|
57 |
+
fig.add_trace(go.Scatter(
|
58 |
+
x=df[anomalies]['timestamp'],
|
59 |
+
y=df[anomalies]['network_traffic'],
|
60 |
+
name='Anomalies',
|
61 |
+
mode='markers',
|
62 |
+
marker=dict(color='red', size=10)
|
63 |
+
))
|
64 |
+
|
65 |
+
fig.update_layout(
|
66 |
+
title='Network Traffic with Anomaly Detection',
|
67 |
+
xaxis_title='Time',
|
68 |
+
yaxis_title='Network Traffic (bytes)',
|
69 |
+
template='plotly_white'
|
70 |
+
)
|
71 |
+
return fig
|
72 |
+
|
73 |
+
# Create metrics
|
74 |
+
def generate_metrics():
|
75 |
+
return {
|
76 |
+
'Total Anomalies': int(sum(anomalies)),
|
77 |
+
'Average Network Traffic': f"{float(df['network_traffic'].mean()):.2f}",
|
78 |
+
'Max Failed Logins': int(df['failed_logins'].max()),
|
79 |
+
}
|
80 |
|
81 |
+
# Define the app layout
|
82 |
app.layout = html.Div([
|
83 |
html.H1("AI-Enhanced Cybersecurity Dashboard",
|
84 |
style={'textAlign': 'center', 'padding': '20px'}),
|
85 |
|
86 |
+
# Metrics Section
|
87 |
html.Div([
|
88 |
html.H2("Key Metrics", style={'textAlign': 'center'}),
|
89 |
+
html.Div([
|
90 |
+
html.Table(
|
91 |
+
[html.Tr([html.Th(k), html.Td(v)]) for k, v in generate_metrics().items()],
|
92 |
+
style={'margin': 'auto', 'border-collapse': 'collapse'}
|
93 |
+
)
|
94 |
+
])
|
95 |
], style={'padding': '20px'}),
|
96 |
|
97 |
+
# Network Traffic Graph
|
98 |
html.Div([
|
99 |
html.H2("Network Traffic Analysis", style={'textAlign': 'center'}),
|
100 |
+
dcc.Graph(figure=create_network_traffic_figure())
|
|
|
|
|
|
|
|
|
|
|
101 |
], style={'padding': '20px'})
|
102 |
])
|
103 |
|
104 |
+
# Add CSS
|
105 |
app.index_string = '''
|
106 |
<!DOCTYPE html>
|
107 |
<html>
|
|
|
116 |
margin: 0;
|
117 |
background-color: #f0f2f5;
|
118 |
}
|
119 |
+
table {
|
120 |
width: 100%;
|
121 |
+
max-width: 600px;
|
|
|
122 |
}
|
123 |
+
th, td {
|
124 |
padding: 12px;
|
125 |
text-align: left;
|
126 |
border-bottom: 1px solid #ddd;
|
127 |
}
|
128 |
+
th {
|
129 |
background-color: #f8f9fa;
|
130 |
}
|
131 |
</style>
|