Anupam202224 commited on
Commit
6d7c397
·
verified ·
1 Parent(s): 8004745

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +214 -0
app.py ADDED
@@ -0,0 +1,214 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ class CyberSecurityAnalytics:
15
+ def __init__(self):
16
+ self.generate_data()
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
+ def plot_network_traffic(self):
46
+ fig = go.Figure()
47
+
48
+ fig.add_trace(go.Scatter(
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
+ def plot_security_overview(self):
73
+ fig = make_subplots(
74
+ rows=3, cols=2,
75
+ subplot_titles=('Network Traffic', 'Failed Login Attempts',
76
+ 'Attack Types', 'Geographic Distribution',
77
+ 'Port Activity', 'Severity Distribution'),
78
+ specs=[[{'type': 'scatter'}, {'type': 'bar'}],
79
+ [{'type': 'pie'}, {'type': 'pie'}],
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
+ def generate_metrics_table(self):
129
+ metrics = {
130
+ 'Total Anomalies': int(self.data['is_anomaly'].sum()),
131
+ 'High Severity Alerts': int(len(self.data[self.data['severity'] == 'High'])),
132
+ 'Average Network Traffic': f"{float(self.data['network_traffic'].mean()):.2f}",
133
+ 'Max Failed Logins': int(self.data['failed_logins'].max()),
134
+ 'Unique Attack Sources': int(self.data['source_country'].nunique()),
135
+ 'Most Common Attack': str(self.data['attack_type'].mode()[0]),
136
+ 'Most Targeted Port': int(self.data['port'].mode()[0])
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
+ # Initialize the Dash app
145
+ app = dash.Dash(__name__)
146
+ server = app.server
147
+
148
+ # Initialize analytics
149
+ security_analytics = CyberSecurityAnalytics()
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
+ security_analytics.generate_metrics_table()
159
+ ], style={'padding': '20px'}),
160
+
161
+ html.Div([
162
+ html.H2("Network Traffic Analysis", style={'textAlign': 'center'}),
163
+ dcc.Graph(figure=security_analytics.plot_network_traffic())
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 some CSS styling
173
+ app.index_string = '''
174
+ <!DOCTYPE html>
175
+ <html>
176
+ <head>
177
+ {%metas%}
178
+ <title>Cybersecurity Dashboard</title>
179
+ {%favicon%}
180
+ {%css%}
181
+ <style>
182
+ body {
183
+ font-family: Arial, sans-serif;
184
+ margin: 0;
185
+ background-color: #f0f2f5;
186
+ }
187
+ .metrics-table {
188
+ width: 100%;
189
+ border-collapse: collapse;
190
+ margin: 20px 0;
191
+ }
192
+ .metrics-table th, .metrics-table td {
193
+ padding: 12px;
194
+ text-align: left;
195
+ border-bottom: 1px solid #ddd;
196
+ }
197
+ .metrics-table th {
198
+ background-color: #f8f9fa;
199
+ }
200
+ </style>
201
+ </head>
202
+ <body>
203
+ {%app_entry%}
204
+ <footer>
205
+ {%config%}
206
+ {%scripts%}
207
+ {%renderer%}
208
+ </footer>
209
+ </body>
210
+ </html>
211
+ '''
212
+
213
+ if __name__ == '__main__':
214
+ app.run_server(debug=True)