Spaces:
Build error
Build error
Download app.py from Sumayyea/cybersecurity-dashboard: direct link, hf CLI and curl.
- Browser
- Download file 33.9 kB
-
https://huggingface.co/spaces/Sumayyea/cybersecurity-dashboard/resolve/main/app.py
- Command line
-
hf download hf://spaces/Sumayyea/cybersecurity-dashboard/app.py
-
curl -L -o app.py https://huggingface.co/spaces/Sumayyea/cybersecurity-dashboard/resolve/main/app.py
33.9 kB
| """ | |
| Cybersecurity Threat Monitoring Dashboard | |
| A comprehensive multi-page dashboard built with Streamlit | |
| Deployed on Hugging Face Spaces | |
| """ | |
| import streamlit as st | |
| import pandas as pd | |
| import numpy as np | |
| import plotly.express as px | |
| import plotly.graph_objects as go | |
| from datetime import datetime, timedelta | |
| import random | |
| import time | |
| # Page configuration | |
| st.set_page_config( | |
| page_title="CyberShield - Threat Monitor", | |
| page_icon="π‘οΈ", | |
| layout="wide", | |
| initial_sidebar_state="expanded" | |
| ) | |
| # Load custom CSS for dark theme | |
| def load_css(): | |
| st.markdown(""" | |
| <style> | |
| /* Main dark theme */ | |
| .stApp { | |
| background-color: #0a0a0f; | |
| } | |
| /* Sidebar styling */ | |
| [data-testid="stSidebar"] { | |
| background-color: #12121a; | |
| border-right: 1px solid #1e1e2e; | |
| } | |
| /* Metric cards */ | |
| .metric-card { | |
| background: linear-gradient(135deg, #1a1a2e 0%, #16213e 100%); | |
| border: 1px solid #0f3460; | |
| border-radius: 10px; | |
| padding: 20px; | |
| text-align: center; | |
| box-shadow: 0 4px 15px rgba(0, 255, 255, 0.1); | |
| } | |
| .metric-value { | |
| font-size: 2.5rem; | |
| font-weight: bold; | |
| color: #00ffff; | |
| text-shadow: 0 0 10px rgba(0, 255, 255, 0.5); | |
| } | |
| .metric-label { | |
| font-size: 0.9rem; | |
| color: #888; | |
| text-transform: uppercase; | |
| letter-spacing: 1px; | |
| } | |
| .metric-critical { color: #ff4757; text-shadow: 0 0 10px rgba(255, 71, 87, 0.5); } | |
| .metric-high { color: #ff7f50; text-shadow: 0 0 10px rgba(255, 127, 80, 0.5); } | |
| .metric-medium { color: #ffa502; text-shadow: 0 0 10px rgba(255, 165, 2, 0.5); } | |
| .metric-low { color: #2ed573; text-shadow: 0 0 10px rgba(46, 213, 115, 0.5); } | |
| /* Alert box */ | |
| .alert-critical { | |
| background: linear-gradient(90deg, rgba(255,71,87,0.2) 0%, rgba(255,71,87,0.05) 100%); | |
| border-left: 4px solid #ff4757; | |
| padding: 15px; | |
| margin: 10px 0; | |
| border-radius: 5px; | |
| } | |
| .alert-high { | |
| background: linear-gradient(90deg, rgba(255,127,80,0.2) 0%, rgba(255,127,80,0.05) 100%); | |
| border-left: 4px solid #ff7f50; | |
| padding: 15px; | |
| margin: 10px 0; | |
| border-radius: 5px; | |
| } | |
| /* Header styling */ | |
| .main-header { | |
| background: linear-gradient(90deg, #0f3460 0%, #1a1a2e 50%, #0f3460 100%); | |
| padding: 20px; | |
| border-radius: 10px; | |
| margin-bottom: 20px; | |
| border: 1px solid #00ffff33; | |
| text-align: center; | |
| } | |
| .main-header h1 { | |
| color: #00ffff; | |
| text-shadow: 0 0 20px rgba(0, 255, 255, 0.5); | |
| margin: 0; | |
| } | |
| /* Table styling */ | |
| .dataframe { | |
| background-color: #1a1a2e !important; | |
| } | |
| /* Status indicators */ | |
| .status-dot { | |
| height: 10px; | |
| width: 10px; | |
| border-radius: 50%; | |
| display: inline-block; | |
| margin-right: 5px; | |
| animation: pulse 2s infinite; | |
| } | |
| .status-active { background-color: #2ed573; } | |
| .status-warning { background-color: #ffa502; } | |
| .status-danger { background-color: #ff4757; } | |
| @keyframes pulse { | |
| 0% { opacity: 1; } | |
| 50% { opacity: 0.5; } | |
| 100% { opacity: 1; } | |
| } | |
| /* Scrollbar styling */ | |
| ::-webkit-scrollbar { | |
| width: 8px; | |
| height: 8px; | |
| } | |
| ::-webkit-scrollbar-track { | |
| background: #1a1a2e; | |
| } | |
| ::-webkit-scrollbar-thumb { | |
| background: #0f3460; | |
| border-radius: 4px; | |
| } | |
| ::-webkit-scrollbar-thumb:hover { | |
| background: #00ffff; | |
| } | |
| </style> | |
| """, unsafe_allow_html=True) | |
| load_css() | |
| # ============== DATA GENERATION ============== | |
| # Cache the data generation to improve performance | |
| def generate_threat_data(num_records=500): | |
| """Generate realistic simulated threat data""" | |
| attack_types = [ | |
| 'DDoS Attack', 'SQL Injection', 'XSS Attack', 'Brute Force', | |
| 'Malware', 'Phishing', 'Ransomware', 'Man-in-the-Middle', | |
| 'Zero-Day Exploit', 'Port Scanning', 'DNS Tunneling', 'Credential Stuffing' | |
| ] | |
| severities = ['Critical', 'High', 'Medium', 'Low'] | |
| severity_weights = [0.1, 0.25, 0.4, 0.25] | |
| statuses = ['Active', 'Mitigated', 'Investigating', 'Blocked'] | |
| status_weights = [0.3, 0.25, 0.25, 0.2] | |
| countries = [ | |
| ('Russia', 'RUS', 55.7558, 37.6173), | |
| ('China', 'CHN', 39.9042, 116.4074), | |
| ('United States', 'USA', 37.0902, -95.7129), | |
| ('North Korea', 'PRK', 39.0392, 125.7625), | |
| ('Iran', 'IRN', 35.6892, 51.3890), | |
| ('Brazil', 'BRA', -14.2350, -51.9253), | |
| ('India', 'IND', 20.5937, 78.9629), | |
| ('Nigeria', 'NGA', 9.0820, 8.6753), | |
| ('Vietnam', 'VNM', 14.0583, 108.2772), | |
| ('Indonesia', 'IDN', -0.7893, 113.9213), | |
| ('Ukraine', 'UKR', 48.3794, 31.1656), | |
| ('Romania', 'ROU', 45.9432, 24.9668), | |
| ('Germany', 'DEU', 51.1657, 10.4515), | |
| ('Netherlands', 'NLD', 52.1326, 5.2913), | |
| ('Turkey', 'TUR', 38.9637, 35.2433) | |
| ] | |
| target_countries = ['United States', 'United Kingdom', 'Germany', 'France', 'Japan', 'Australia', 'Canada'] | |
| common_ports = [22, 23, 25, 53, 80, 443, 445, 3306, 3389, 5432, 8080, 8443, 27017] | |
| protocols = ['TCP', 'UDP', 'ICMP', 'HTTP', 'HTTPS', 'SSH', 'FTP', 'SMTP', 'DNS'] | |
| # Generate timestamps over the last 7 days | |
| end_time = datetime.now() | |
| start_time = end_time - timedelta(days=7) | |
| data = [] | |
| for i in range(num_records): | |
| country_data = random.choice(countries) | |
| timestamp = start_time + timedelta( | |
| seconds=random.randint(0, int((end_time - start_time).total_seconds())) | |
| ) | |
| # Generate realistic IP | |
| source_ip = f"{random.randint(1,223)}.{random.randint(0,255)}.{random.randint(0,255)}.{random.randint(1,254)}" | |
| dest_ip = f"192.168.{random.randint(1,10)}.{random.randint(1,254)}" | |
| attack_type = random.choice(attack_types) | |
| severity = random.choices(severities, weights=severity_weights)[0] | |
| data.append({ | |
| 'id': f'THR-{str(i+1).zfill(6)}', | |
| 'timestamp': timestamp, | |
| 'attack_type': attack_type, | |
| 'severity': severity, | |
| 'source_ip': source_ip, | |
| 'source_country': country_data[0], | |
| 'country_code': country_data[1], | |
| 'latitude': country_data[2] + random.uniform(-5, 5), | |
| 'longitude': country_data[3] + random.uniform(-5, 5), | |
| 'destination_ip': dest_ip, | |
| 'target_country': random.choice(target_countries), | |
| 'port': random.choice(common_ports), | |
| 'protocol': random.choice(protocols), | |
| 'status': random.choices(statuses, weights=status_weights)[0], | |
| 'packets': random.randint(100, 100000), | |
| 'bytes': random.randint(10000, 10000000), | |
| 'confidence': random.randint(60, 99) | |
| }) | |
| return pd.DataFrame(data) | |
| def generate_network_metrics(): | |
| """Generate network traffic metrics""" | |
| return { | |
| 'total_bandwidth': random.uniform(500, 1000), | |
| 'incoming_traffic': random.uniform(200, 500), | |
| 'outgoing_traffic': random.uniform(150, 400), | |
| 'blocked_requests': random.randint(1000, 5000), | |
| 'active_connections': random.randint(500, 2000), | |
| 'avg_response_time': random.uniform(10, 100), | |
| 'uptime': 99.97, | |
| 'threats_blocked_today': random.randint(100, 500) | |
| } | |
| def generate_alerts(df): | |
| """Generate recent critical alerts""" | |
| critical_threats = df[df['severity'].isin(['Critical', 'High'])].sort_values('timestamp', ascending=False).head(10) | |
| return critical_threats | |
| # ============== SIDEBAR ============== | |
| def render_sidebar(): | |
| with st.sidebar: | |
| st.markdown(""" | |
| <div style='text-align: center; padding: 20px 0;'> | |
| <h1 style='color: #00ffff; font-size: 1.8rem;'>π‘οΈ CyberShield</h1> | |
| <p style='color: #888; font-size: 0.8rem;'>Threat Monitoring System v2.0</p> | |
| </div> | |
| """, unsafe_allow_html=True) | |
| st.markdown("---") | |
| # Navigation | |
| st.markdown("### π Navigation") | |
| page = st.radio( | |
| "Select Page", | |
| ["π Overview", "π Threat Feed", "π Geographic Analysis", "π Network Analysis", "π¨ Alerts"], | |
| label_visibility="collapsed" | |
| ) | |
| st.markdown("---") | |
| # Filters | |
| st.markdown("### π Filters") | |
| # Date range filter | |
| date_range = st.date_input( | |
| "Date Range", | |
| value=(datetime.now() - timedelta(days=7), datetime.now()), | |
| max_value=datetime.now() | |
| ) | |
| # Severity filter | |
| severity_filter = st.multiselect( | |
| "Severity", | |
| ["Critical", "High", "Medium", "Low"], | |
| default=["Critical", "High", "Medium", "Low"] | |
| ) | |
| # Attack type filter | |
| attack_types = [ | |
| 'DDoS Attack', 'SQL Injection', 'XSS Attack', 'Brute Force', | |
| 'Malware', 'Phishing', 'Ransomware', 'Man-in-the-Middle', | |
| 'Zero-Day Exploit', 'Port Scanning', 'DNS Tunneling', 'Credential Stuffing' | |
| ] | |
| attack_filter = st.multiselect( | |
| "Attack Types", | |
| attack_types, | |
| default=attack_types | |
| ) | |
| st.markdown("---") | |
| # System status | |
| st.markdown("### π» System Status") | |
| st.markdown(""" | |
| <div style='padding: 10px; background: #1a1a2e; border-radius: 5px;'> | |
| <p><span class='status-dot status-active'></span> Firewall: Active</p> | |
| <p><span class='status-dot status-active'></span> IDS/IPS: Active</p> | |
| <p><span class='status-dot status-active'></span> SIEM: Connected</p> | |
| <p><span class='status-dot status-warning'></span> Threat Intel: Updating</p> | |
| </div> | |
| """, unsafe_allow_html=True) | |
| st.markdown("---") | |
| st.markdown(""" | |
| <div style='text-align: center; color: #666; font-size: 0.7rem;'> | |
| <p>Last Updated: """ + datetime.now().strftime("%Y-%m-%d %H:%M:%S") + """</p> | |
| <p>Β© 2024 CyberShield</p> | |
| </div> | |
| """, unsafe_allow_html=True) | |
| return page, date_range, severity_filter, attack_filter | |
| # ============== PAGE FUNCTIONS ============== | |
| def overview_page(df, metrics): | |
| """Main overview dashboard page""" | |
| # Header | |
| st.markdown(""" | |
| <div class='main-header'> | |
| <h1>π‘οΈ CYBERSHIELD THREAT MONITOR</h1> | |
| <p style='color: #888;'>Real-time Security Operations Dashboard</p> | |
| </div> | |
| """, unsafe_allow_html=True) | |
| # Key metrics row | |
| col1, col2, col3, col4, col5 = st.columns(5) | |
| total_threats = len(df) | |
| critical_count = len(df[df['severity'] == 'Critical']) | |
| high_count = len(df[df['severity'] == 'High']) | |
| blocked_count = len(df[df['status'] == 'Blocked']) | |
| active_count = len(df[df['status'] == 'Active']) | |
| with col1: | |
| st.markdown(f""" | |
| <div class='metric-card'> | |
| <div class='metric-value'>{total_threats:,}</div> | |
| <div class='metric-label'>Total Threats</div> | |
| </div> | |
| """, unsafe_allow_html=True) | |
| with col2: | |
| st.markdown(f""" | |
| <div class='metric-card'> | |
| <div class='metric-value metric-critical'>{critical_count}</div> | |
| <div class='metric-label'>Critical</div> | |
| </div> | |
| """, unsafe_allow_html=True) | |
| with col3: | |
| st.markdown(f""" | |
| <div class='metric-card'> | |
| <div class='metric-value metric-high'>{high_count}</div> | |
| <div class='metric-label'>High Severity</div> | |
| </div> | |
| """, unsafe_allow_html=True) | |
| with col4: | |
| st.markdown(f""" | |
| <div class='metric-card'> | |
| <div class='metric-value metric-low'>{blocked_count}</div> | |
| <div class='metric-label'>Blocked</div> | |
| </div> | |
| """, unsafe_allow_html=True) | |
| with col5: | |
| st.markdown(f""" | |
| <div class='metric-card'> | |
| <div class='metric-value' style='color: #ff6b6b;'>{active_count}</div> | |
| <div class='metric-label'>Active Threats</div> | |
| </div> | |
| """, unsafe_allow_html=True) | |
| st.markdown("<br>", unsafe_allow_html=True) | |
| # Charts row 1 | |
| col1, col2 = st.columns(2) | |
| with col1: | |
| st.markdown("### π Threat Timeline (7 Days)") | |
| df_timeline = df.copy() | |
| df_timeline['date'] = df_timeline['timestamp'].dt.date | |
| timeline_data = df_timeline.groupby(['date', 'severity']).size().reset_index(name='count') | |
| fig_timeline = px.area( | |
| timeline_data, | |
| x='date', | |
| y='count', | |
| color='severity', | |
| color_discrete_map={ | |
| 'Critical': '#ff4757', | |
| 'High': '#ff7f50', | |
| 'Medium': '#ffa502', | |
| 'Low': '#2ed573' | |
| } | |
| ) | |
| fig_timeline.update_layout( | |
| plot_bgcolor='rgba(0,0,0,0)', | |
| paper_bgcolor='rgba(0,0,0,0)', | |
| font_color='#888', | |
| legend=dict(orientation="h", yanchor="bottom", y=1.02, xanchor="right", x=1), | |
| margin=dict(l=0, r=0, t=30, b=0), | |
| xaxis=dict(gridcolor='#1a1a2e'), | |
| yaxis=dict(gridcolor='#1a1a2e') | |
| ) | |
| st.plotly_chart(fig_timeline, use_container_width=True) | |
| with col2: | |
| st.markdown("### π― Threat Severity Distribution") | |
| severity_counts = df['severity'].value_counts() | |
| fig_severity = go.Figure(data=[go.Pie( | |
| labels=severity_counts.index, | |
| values=severity_counts.values, | |
| hole=0.6, | |
| marker_colors=['#ff4757', '#ff7f50', '#ffa502', '#2ed573'] | |
| )]) | |
| fig_severity.update_layout( | |
| plot_bgcolor='rgba(0,0,0,0)', | |
| paper_bgcolor='rgba(0,0,0,0)', | |
| font_color='#888', | |
| showlegend=True, | |
| legend=dict(orientation="h", yanchor="bottom", y=-0.1, xanchor="center", x=0.5), | |
| margin=dict(l=0, r=0, t=30, b=0), | |
| annotations=[dict(text='Threats', x=0.5, y=0.5, font_size=16, showarrow=False, font_color='#00ffff')] | |
| ) | |
| st.plotly_chart(fig_severity, use_container_width=True) | |
| # Charts row 2 | |
| col1, col2 = st.columns(2) | |
| with col1: | |
| st.markdown("### βοΈ Attack Type Distribution") | |
| attack_counts = df['attack_type'].value_counts().head(10) | |
| fig_attacks = px.bar( | |
| x=attack_counts.values, | |
| y=attack_counts.index, | |
| orientation='h', | |
| color=attack_counts.values, | |
| color_continuous_scale='Tealgrn' | |
| ) | |
| fig_attacks.update_layout( | |
| plot_bgcolor='rgba(0,0,0,0)', | |
| paper_bgcolor='rgba(0,0,0,0)', | |
| font_color='#888', | |
| showlegend=False, | |
| margin=dict(l=0, r=0, t=10, b=0), | |
| xaxis=dict(gridcolor='#1a1a2e', title='Count'), | |
| yaxis=dict(gridcolor='#1a1a2e', title=''), | |
| coloraxis_showscale=False | |
| ) | |
| st.plotly_chart(fig_attacks, use_container_width=True) | |
| with col2: | |
| st.markdown("### π Top Targeted Ports") | |
| port_counts = df['port'].value_counts().head(10) | |
| fig_ports = px.bar( | |
| x=port_counts.index.astype(str), | |
| y=port_counts.values, | |
| color=port_counts.values, | |
| color_continuous_scale='Reds' | |
| ) | |
| fig_ports.update_layout( | |
| plot_bgcolor='rgba(0,0,0,0)', | |
| paper_bgcolor='rgba(0,0,0,0)', | |
| font_color='#888', | |
| showlegend=False, | |
| margin=dict(l=0, r=0, t=10, b=0), | |
| xaxis=dict(gridcolor='#1a1a2e', title='Port'), | |
| yaxis=dict(gridcolor='#1a1a2e', title='Attacks'), | |
| coloraxis_showscale=False | |
| ) | |
| st.plotly_chart(fig_ports, use_container_width=True) | |
| # Recent alerts section | |
| st.markdown("### π¨ Recent Critical Alerts") | |
| recent_critical = df[df['severity'].isin(['Critical', 'High'])].sort_values('timestamp', ascending=False).head(5) | |
| for _, alert in recent_critical.iterrows(): | |
| alert_class = 'alert-critical' if alert['severity'] == 'Critical' else 'alert-high' | |
| st.markdown(f""" | |
| <div class='{alert_class}'> | |
| <strong>{alert['severity'].upper()}</strong> | {alert['attack_type']} | | |
| Source: {alert['source_ip']} ({alert['source_country']}) | | |
| Target Port: {alert['port']} | | |
| {alert['timestamp'].strftime('%Y-%m-%d %H:%M:%S')} | |
| </div> | |
| """, unsafe_allow_html=True) | |
| def threat_feed_page(df): | |
| """Threat feed page with detailed table""" | |
| st.markdown("## π Live Threat Feed") | |
| st.markdown("Real-time view of all detected threats with detailed information") | |
| # Search functionality | |
| search = st.text_input("π Search (IP, Attack Type, Country)", "") | |
| # Apply search filter | |
| if search: | |
| mask = ( | |
| df['source_ip'].str.contains(search, case=False, na=False) | | |
| df['attack_type'].str.contains(search, case=False, na=False) | | |
| df['source_country'].str.contains(search, case=False, na=False) | |
| ) | |
| filtered_df = df[mask] | |
| else: | |
| filtered_df = df | |
| # Sort by timestamp | |
| filtered_df = filtered_df.sort_values('timestamp', ascending=False) | |
| # Display metrics | |
| col1, col2, col3, col4 = st.columns(4) | |
| col1.metric("Total Records", len(filtered_df)) | |
| col2.metric("Critical", len(filtered_df[filtered_df['severity'] == 'Critical'])) | |
| col3.metric("Active", len(filtered_df[filtered_df['status'] == 'Active'])) | |
| col4.metric("Blocked", len(filtered_df[filtered_df['status'] == 'Blocked'])) | |
| # Format dataframe for display | |
| display_df = filtered_df[[ | |
| 'id', 'timestamp', 'attack_type', 'severity', 'source_ip', | |
| 'source_country', 'port', 'protocol', 'status', 'confidence' | |
| ]].copy() | |
| display_df['timestamp'] = display_df['timestamp'].dt.strftime('%Y-%m-%d %H:%M:%S') | |
| display_df.columns = ['ID', 'Timestamp', 'Attack Type', 'Severity', 'Source IP', | |
| 'Country', 'Port', 'Protocol', 'Status', 'Confidence %'] | |
| # Color code severity | |
| def highlight_severity(row): | |
| colors = { | |
| 'Critical': 'background-color: rgba(255,71,87,0.3)', | |
| 'High': 'background-color: rgba(255,127,80,0.3)', | |
| 'Medium': 'background-color: rgba(255,165,2,0.3)', | |
| 'Low': 'background-color: rgba(46,213,115,0.3)' | |
| } | |
| return [colors.get(row['Severity'], '')] * len(row) | |
| st.dataframe( | |
| display_df.head(100).style.apply(highlight_severity, axis=1), | |
| use_container_width=True, | |
| height=600 | |
| ) | |
| st.info(f"Showing {min(100, len(display_df))} of {len(display_df)} records") | |
| def geographic_page(df): | |
| """Geographic analysis page with world map""" | |
| st.markdown("## π Geographic Threat Analysis") | |
| st.markdown("Visualize attack origins and target locations worldwide") | |
| col1, col2 = st.columns([2, 1]) | |
| with col1: | |
| st.markdown("### πΊοΈ Global Attack Origins") | |
| # Aggregate by country for bubble size | |
| country_stats = df.groupby(['source_country', 'country_code', 'latitude', 'longitude']).agg({ | |
| 'id': 'count', | |
| 'severity': lambda x: (x == 'Critical').sum() | |
| }).reset_index() | |
| country_stats.columns = ['country', 'code', 'lat', 'lon', 'total_attacks', 'critical_attacks'] | |
| # Create map | |
| fig_map = px.scatter_geo( | |
| country_stats, | |
| lat='lat', | |
| lon='lon', | |
| size='total_attacks', | |
| color='critical_attacks', | |
| hover_name='country', | |
| hover_data={'total_attacks': True, 'critical_attacks': True, 'lat': False, 'lon': False}, | |
| color_continuous_scale='Reds', | |
| size_max=50, | |
| projection='natural earth' | |
| ) | |
| fig_map.update_layout( | |
| geo=dict( | |
| bgcolor='rgba(0,0,0,0)', | |
| landcolor='#1a1a2e', | |
| oceancolor='#0a0a0f', | |
| countrycolor='#333', | |
| coastlinecolor='#333', | |
| showocean=True, | |
| showland=True, | |
| showcountries=True | |
| ), | |
| plot_bgcolor='rgba(0,0,0,0)', | |
| paper_bgcolor='rgba(0,0,0,0)', | |
| font_color='#888', | |
| margin=dict(l=0, r=0, t=0, b=0), | |
| coloraxis_colorbar=dict(title='Critical') | |
| ) | |
| st.plotly_chart(fig_map, use_container_width=True) | |
| with col2: | |
| st.markdown("### π΄ Top Attack Sources") | |
| top_countries = df['source_country'].value_counts().head(10) | |
| fig_countries = px.bar( | |
| x=top_countries.values, | |
| y=top_countries.index, | |
| orientation='h', | |
| color=top_countries.values, | |
| color_continuous_scale='Reds' | |
| ) | |
| fig_countries.update_layout( | |
| plot_bgcolor='rgba(0,0,0,0)', | |
| paper_bgcolor='rgba(0,0,0,0)', | |
| font_color='#888', | |
| showlegend=False, | |
| margin=dict(l=0, r=0, t=10, b=0), | |
| xaxis=dict(gridcolor='#1a1a2e', title='Attacks'), | |
| yaxis=dict(gridcolor='#1a1a2e', title=''), | |
| coloraxis_showscale=False, | |
| height=400 | |
| ) | |
| st.plotly_chart(fig_countries, use_container_width=True) | |
| # Target countries | |
| col1, col2 = st.columns(2) | |
| with col1: | |
| st.markdown("### π― Top Targeted Countries") | |
| target_counts = df['target_country'].value_counts() | |
| fig_targets = px.pie( | |
| values=target_counts.values, | |
| names=target_counts.index, | |
| hole=0.4, | |
| color_discrete_sequence=px.colors.sequential.Tealgrn | |
| ) | |
| fig_targets.update_layout( | |
| plot_bgcolor='rgba(0,0,0,0)', | |
| paper_bgcolor='rgba(0,0,0,0)', | |
| font_color='#888', | |
| margin=dict(l=0, r=0, t=10, b=0) | |
| ) | |
| st.plotly_chart(fig_targets, use_container_width=True) | |
| with col2: | |
| st.markdown("### π Attack Flow by Country") | |
| # Country-wise severity breakdown | |
| country_severity = df.groupby(['source_country', 'severity']).size().reset_index(name='count') | |
| country_severity = country_severity[country_severity['source_country'].isin(top_countries.index[:8])] | |
| fig_flow = px.bar( | |
| country_severity, | |
| x='source_country', | |
| y='count', | |
| color='severity', | |
| barmode='stack', | |
| color_discrete_map={ | |
| 'Critical': '#ff4757', | |
| 'High': '#ff7f50', | |
| 'Medium': '#ffa502', | |
| 'Low': '#2ed573' | |
| } | |
| ) | |
| fig_flow.update_layout( | |
| plot_bgcolor='rgba(0,0,0,0)', | |
| paper_bgcolor='rgba(0,0,0,0)', | |
| font_color='#888', | |
| margin=dict(l=0, r=0, t=10, b=0), | |
| xaxis=dict(gridcolor='#1a1a2e', title=''), | |
| yaxis=dict(gridcolor='#1a1a2e', title='Attacks'), | |
| legend=dict(orientation="h", yanchor="bottom", y=1.02, xanchor="right", x=1) | |
| ) | |
| st.plotly_chart(fig_flow, use_container_width=True) | |
| def network_page(df, metrics): | |
| """Network analysis page""" | |
| st.markdown("## π Network Analysis") | |
| st.markdown("Monitor network traffic and identify suspicious patterns") | |
| # Network metrics | |
| col1, col2, col3, col4 = st.columns(4) | |
| with col1: | |
| st.markdown(f""" | |
| <div class='metric-card'> | |
| <div class='metric-value'>{metrics['total_bandwidth']:.1f}</div> | |
| <div class='metric-label'>Bandwidth (Gbps)</div> | |
| </div> | |
| """, unsafe_allow_html=True) | |
| with col2: | |
| st.markdown(f""" | |
| <div class='metric-card'> | |
| <div class='metric-value'>{metrics['active_connections']:,}</div> | |
| <div class='metric-label'>Active Connections</div> | |
| </div> | |
| """, unsafe_allow_html=True) | |
| with col3: | |
| st.markdown(f""" | |
| <div class='metric-card'> | |
| <div class='metric-value metric-low'>{metrics['uptime']}%</div> | |
| <div class='metric-label'>System Uptime</div> | |
| </div> | |
| """, unsafe_allow_html=True) | |
| with col4: | |
| st.markdown(f""" | |
| <div class='metric-card'> | |
| <div class='metric-value'>{metrics['avg_response_time']:.1f}ms</div> | |
| <div class='metric-label'>Avg Response Time</div> | |
| </div> | |
| """, unsafe_allow_html=True) | |
| st.markdown("<br>", unsafe_allow_html=True) | |
| # Charts | |
| col1, col2 = st.columns(2) | |
| with col1: | |
| st.markdown("### π Top Attacker IPs") | |
| top_ips = df.groupby('source_ip').agg({ | |
| 'id': 'count', | |
| 'severity': lambda x: (x == 'Critical').sum(), | |
| 'source_country': 'first' | |
| }).reset_index() | |
| top_ips.columns = ['IP Address', 'Total Attacks', 'Critical', 'Country'] | |
| top_ips = top_ips.sort_values('Total Attacks', ascending=False).head(10) | |
| st.dataframe( | |
| top_ips, | |
| use_container_width=True, | |
| hide_index=True | |
| ) | |
| with col2: | |
| st.markdown("### π‘ Protocol Distribution") | |
| protocol_counts = df['protocol'].value_counts() | |
| fig_protocol = px.pie( | |
| values=protocol_counts.values, | |
| names=protocol_counts.index, | |
| color_discrete_sequence=px.colors.sequential.Plasma | |
| ) | |
| fig_protocol.update_layout( | |
| plot_bgcolor='rgba(0,0,0,0)', | |
| paper_bgcolor='rgba(0,0,0,0)', | |
| font_color='#888', | |
| margin=dict(l=0, r=0, t=10, b=0) | |
| ) | |
| st.plotly_chart(fig_protocol, use_container_width=True) | |
| # Traffic gauge | |
| col1, col2 = st.columns(2) | |
| with col1: | |
| st.markdown("### π₯ Incoming Traffic") | |
| fig_in = go.Figure(go.Indicator( | |
| mode="gauge+number", | |
| value=metrics['incoming_traffic'], | |
| title={'text': "Gbps", 'font': {'color': '#888'}}, | |
| gauge={ | |
| 'axis': {'range': [0, 600], 'tickcolor': '#888'}, | |
| 'bar': {'color': '#00ffff'}, | |
| 'bgcolor': '#1a1a2e', | |
| 'bordercolor': '#333', | |
| 'steps': [ | |
| {'range': [0, 200], 'color': '#1a3a1a'}, | |
| {'range': [200, 400], 'color': '#3a3a1a'}, | |
| {'range': [400, 600], 'color': '#3a1a1a'} | |
| ] | |
| } | |
| )) | |
| fig_in.update_layout( | |
| plot_bgcolor='rgba(0,0,0,0)', | |
| paper_bgcolor='rgba(0,0,0,0)', | |
| font_color='#888', | |
| height=250, | |
| margin=dict(l=20, r=20, t=40, b=20) | |
| ) | |
| st.plotly_chart(fig_in, use_container_width=True) | |
| with col2: | |
| st.markdown("### π€ Outgoing Traffic") | |
| fig_out = go.Figure(go.Indicator( | |
| mode="gauge+number", | |
| value=metrics['outgoing_traffic'], | |
| title={'text': "Gbps", 'font': {'color': '#888'}}, | |
| gauge={ | |
| 'axis': {'range': [0, 600], 'tickcolor': '#888'}, | |
| 'bar': {'color': '#2ed573'}, | |
| 'bgcolor': '#1a1a2e', | |
| 'bordercolor': '#333', | |
| 'steps': [ | |
| {'range': [0, 200], 'color': '#1a3a1a'}, | |
| {'range': [200, 400], 'color': '#3a3a1a'}, | |
| {'range': [400, 600], 'color': '#3a1a1a'} | |
| ] | |
| } | |
| )) | |
| fig_out.update_layout( | |
| plot_bgcolor='rgba(0,0,0,0)', | |
| paper_bgcolor='rgba(0,0,0,0)', | |
| font_color='#888', | |
| height=250, | |
| margin=dict(l=20, r=20, t=40, b=20) | |
| ) | |
| st.plotly_chart(fig_out, use_container_width=True) | |
| # Hourly traffic pattern | |
| st.markdown("### π Hourly Traffic Pattern") | |
| df_hourly = df.copy() | |
| df_hourly['hour'] = df_hourly['timestamp'].dt.hour | |
| hourly_counts = df_hourly.groupby('hour').size().reset_index(name='attacks') | |
| fig_hourly = px.line( | |
| hourly_counts, | |
| x='hour', | |
| y='attacks', | |
| markers=True | |
| ) | |
| fig_hourly.update_traces(line_color='#00ffff', marker_color='#00ffff') | |
| fig_hourly.update_layout( | |
| plot_bgcolor='rgba(0,0,0,0)', | |
| paper_bgcolor='rgba(0,0,0,0)', | |
| font_color='#888', | |
| margin=dict(l=0, r=0, t=10, b=0), | |
| xaxis=dict(gridcolor='#1a1a2e', title='Hour of Day', dtick=2), | |
| yaxis=dict(gridcolor='#1a1a2e', title='Number of Attacks') | |
| ) | |
| st.plotly_chart(fig_hourly, use_container_width=True) | |
| def alerts_page(df): | |
| """Alerts and notifications page""" | |
| st.markdown("## π¨ Security Alerts") | |
| st.markdown("Critical and high-severity alerts requiring immediate attention") | |
| # Alert summary | |
| critical_alerts = df[df['severity'] == 'Critical'] | |
| high_alerts = df[df['severity'] == 'High'] | |
| active_alerts = df[df['status'] == 'Active'] | |
| col1, col2, col3, col4 = st.columns(4) | |
| with col1: | |
| st.markdown(f""" | |
| <div class='metric-card'> | |
| <div class='metric-value metric-critical'>{len(critical_alerts)}</div> | |
| <div class='metric-label'>Critical Alerts</div> | |
| </div> | |
| """, unsafe_allow_html=True) | |
| with col2: | |
| st.markdown(f""" | |
| <div class='metric-card'> | |
| <div class='metric-value metric-high'>{len(high_alerts)}</div> | |
| <div class='metric-label'>High Alerts</div> | |
| </div> | |
| """, unsafe_allow_html=True) | |
| with col3: | |
| st.markdown(f""" | |
| <div class='metric-card'> | |
| <div class='metric-value' style='color: #ff6b6b;'>{len(active_alerts)}</div> | |
| <div class='metric-label'>Active Threats</div> | |
| </div> | |
| """, unsafe_allow_html=True) | |
| with col4: | |
| mitigated = len(df[df['status'] == 'Mitigated']) | |
| st.markdown(f""" | |
| <div class='metric-card'> | |
| <div class='metric-value metric-low'>{mitigated}</div> | |
| <div class='metric-label'>Mitigated</div> | |
| </div> | |
| """, unsafe_allow_html=True) | |
| st.markdown("<br>", unsafe_allow_html=True) | |
| # Critical alerts list | |
| st.markdown("### π΄ Critical Alerts") | |
| critical_list = critical_alerts.sort_values('timestamp', ascending=False).head(15) | |
| for _, alert in critical_list.iterrows(): | |
| with st.expander(f"β οΈ {alert['id']} - {alert['attack_type']} | {alert['timestamp'].strftime('%Y-%m-%d %H:%M:%S')}"): | |
| col1, col2, col3 = st.columns(3) | |
| with col1: | |
| st.markdown(f""" | |
| **Source IP:** {alert['source_ip']} | |
| **Country:** {alert['source_country']} | |
| **Protocol:** {alert['protocol']} | |
| """) | |
| with col2: | |
| st.markdown(f""" | |
| **Target Port:** {alert['port']} | |
| **Target Country:** {alert['target_country']} | |
| **Destination IP:** {alert['destination_ip']} | |
| """) | |
| with col3: | |
| st.markdown(f""" | |
| **Status:** {alert['status']} | |
| **Confidence:** {alert['confidence']}% | |
| **Packets:** {alert['packets']:,} | |
| """) | |
| st.progress(alert['confidence'] / 100) | |
| col1, col2, col3 = st.columns(3) | |
| with col1: | |
| st.button("π‘οΈ Block IP", key=f"block_{alert['id']}") | |
| with col2: | |
| st.button("π Investigate", key=f"inv_{alert['id']}") | |
| with col3: | |
| st.button("β Mark Resolved", key=f"resolve_{alert['id']}") | |
| st.markdown("---") | |
| # High severity alerts | |
| st.markdown("### π High Severity Alerts") | |
| high_list = high_alerts.sort_values('timestamp', ascending=False).head(10) | |
| for _, alert in high_list.iterrows(): | |
| st.markdown(f""" | |
| <div class='alert-high'> | |
| <strong>{alert['id']}</strong> | {alert['attack_type']} | | |
| Source: {alert['source_ip']} ({alert['source_country']}) β | |
| Port {alert['port']} | Status: {alert['status']} | | |
| {alert['timestamp'].strftime('%Y-%m-%d %H:%M:%S')} | |
| </div> | |
| """, unsafe_allow_html=True) | |
| # ============== MAIN APP ============== | |
| def main(): | |
| # Get sidebar selections | |
| page, date_range, severity_filter, attack_filter = render_sidebar() | |
| # Generate data | |
| df = generate_threat_data(500) | |
| metrics = generate_network_metrics() | |
| # Apply filters | |
| if len(date_range) == 2: | |
| start_date, end_date = date_range | |
| df = df[(df['timestamp'].dt.date >= start_date) & (df['timestamp'].dt.date <= end_date)] | |
| df = df[df['severity'].isin(severity_filter)] | |
| df = df[df['attack_type'].isin(attack_filter)] | |
| # Render selected page | |
| if page == "π Overview": | |
| overview_page(df, metrics) | |
| elif page == "π Threat Feed": | |
| threat_feed_page(df) | |
| elif page == "π Geographic Analysis": | |
| geographic_page(df) | |
| elif page == "π Network Analysis": | |
| network_page(df, metrics) | |
| elif page == "π¨ Alerts": | |
| alerts_page(df) | |
| if __name__ == "__main__": | |
| main() | |