Skip to content

isaac0621/SecuScan

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

6 Commits
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

πŸ”’ SecuScan Dashboard - Security Log Visualization & Analysis

A full-stack security dashboard that demonstrates cybersecurity expertise through log analysis, intrusion detection, and secure API design. Built with React, Vite, Python Flask, and JWT authentication.

πŸ“‹ Project Overview

SecuScan simulates a real security operations center (SOC) dashboard by:

  • Parsing security logs from a server and detecting intrusion patterns
  • Visualizing threats with interactive charts (failed login attempts, traffic by country, alert severity)
  • Implementing JWT authentication to protect sensitive endpoints
  • Detecting attack patterns: SQL injection, brute force, path traversal, DDoS indicators
  • Providing real-time analysis with automatic data refresh

πŸš€ Quick Start

Installation

# Navigate to project root
cd SecuScan

# Install all dependencies
npm run install-all

Running Everything with One Command

npm start

This command uses concurrently to run:

  • Backend: Flask server on http://localhost:5000
  • Frontend: Vite dev server on http://localhost:5173

Demo Credentials

Username: admin
Password: admin123

πŸ“ Project Structure

SecuScan/
β”œβ”€β”€ client/                 # React + Vite Frontend
β”‚   β”œβ”€β”€ src/
β”‚   β”‚   β”œβ”€β”€ components/
β”‚   β”‚   β”‚   β”œβ”€β”€ Dashboard.jsx      # Main dashboard with charts
β”‚   β”‚   β”‚   └── Dashboard.css
β”‚   β”‚   β”œβ”€β”€ App.jsx                # Login & theme management
β”‚   β”‚   β”œβ”€β”€ App.css
β”‚   β”‚   β”œβ”€β”€ main.jsx
β”‚   β”‚   └── index.css
β”‚   β”œβ”€β”€ vite.config.js             # Vite configuration with proxy
β”‚   β”œβ”€β”€ index.html
β”‚   └── package.json
β”‚
β”œβ”€β”€ server/                 # Python Flask Backend
β”‚   β”œβ”€β”€ main.py                    # Flask API with JWT auth
β”‚   β”œβ”€β”€ security.log               # Sample security logs
β”‚   └── requirements.txt
β”‚
β”œβ”€β”€ package.json            # Root monorepo config with concurrently
└── README.md

πŸ” Security Features

Authentication & Authorization

JWT Token Implementation

# Token generation (secure)
token = jwt.encode(
    {
        'user': username,
        'exp': datetime.utcnow() + timedelta(hours=24)
    },
    SECRET_KEY,
    algorithm='HS256'
)

# Token validation on protected endpoints
@token_required
def get_logs(current_user):
    # Only authenticated users can access
    return jsonify({'logs': SECURITY_LOGS})

Security Benefits:

  • βœ… Stateless authentication (no session storage needed)
  • βœ… Token expiration (24-hour validity)
  • βœ… HS256 signing algorithm for integrity
  • βœ… Authorization header validation

Input Validation & Sanitization

# Credential validation
if not data or not data.get('username') or not data.get('password'):
    return jsonify({'error': 'Missing credentials'}), 400

username = data['username'].strip()  # Remove whitespace

Protection Against:

  • βœ… Missing/null fields
  • βœ… Whitespace injection

Request Size Limiting

@app.before_request
def limit_request_size():
    """Prevent DoS attacks via large payloads"""
    if request.content_length and request.content_length > 1024 * 1024:
        return jsonify({'error': 'Request payload too large'}), 413

Protection Against:

  • βœ… Denial of Service (DoS) attacks
  • βœ… Buffer overflow attempts
  • βœ… Memory exhaustion

CORS Security

CORS(app)  # Configured with Flask-CORS

Implementation:

  • βœ… Allows frontend-backend communication
  • βœ… Prevents unauthorized cross-origin requests
  • βœ… Can be restricted to specific origins in production

Pattern-Based Attack Detection

The backend detects multiple attack vectors:

SQL Injection Detection

sql_injection_pattern = r'(union|select|drop|insert|update|delete|--|;|OR|AND).*=.*'

Detects: UNION-based injection, DROP TABLE, comment-based injection

Path Traversal Detection

path_traversal_pattern = r'(\.\./|\.\.\\|%2e%2e)'

Detects: ../../etc/passwd, ..\...\windows\system32

Brute Force Detection

# Count failed login attempts per IP
if count >= 10:  # 10+ failures = suspicious
    analysis['suspicious_ips'].append({'ip': ip, 'failed_attempts': count})

Vulnerability Scanner Detection

suspicious_agents = ['sqlmap', 'nikto', 'nmap', 'masscan']

🎨 Frontend Features

Dark Mode (Hacker Aesthetic)

  • Toggle between dark and light themes
  • Persists across sessions
  • Gradient backgrounds and neon colors
  • Optimized for extended viewing

Interactive Dashboards

1. Real-Time Statistics

  • Total Requests processed
  • Critical Alerts (with pulse animation)
  • Failed Login Attempts
  • Unique IPs detected

2. Security Charts

  • Failed Logins Timeline: Line chart showing brute force attacks over time
  • Traffic by Country: Bar chart for geographic threat analysis
  • Alert Severity Distribution: Pie chart (Critical, High, Medium, Low)

3. Security Event Log

  • Real-time event table with 50+ sample logs
  • Color-coded severity levels
  • IP, timestamp, event type, and status columns
  • Auto-refresh every 10 seconds

Responsive Design

  • Mobile-first approach
  • Works on desktop, tablet, and mobile
  • Scales beautifully from 320px to 4K displays

πŸ”§ Backend API Endpoints

Authentication

POST /api/auth/login

Authenticate user and receive JWT token.

Request:

{
  "username": "admin",
  "password": "admin123"
}

Response:

{
  "token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..."
}

Protected Endpoints (Require JWT Token)

GET /api/logs

Retrieve all parsed security logs.

Headers:

Authorization: Bearer {token}

Response:

{
  "logs": [
    {
      "timestamp": "2024-01-19 08:15:23",
      "ip": "192.168.1.105",
      "event_type": "Failed Login",
      "status": "failed",
      "details": "Invalid password attempt",
      "severity": "high"
    }
  ]
}

GET /api/analysis

Get intrusion detection analysis and threat intelligence.

Headers:

Authorization: Bearer {token}

Response:

{
  "total_requests": 50,
  "critical_alerts": 2,
  "high_alerts": 8,
  "medium_alerts": 5,
  "low_alerts": 10,
  "failed_logins_count": 12,
  "unique_ips": 15,
  "failed_logins": [
    {"time": "2024-01-19 08", "count": 12}
  ],
  "traffic_by_country": [
    {"country": "USA", "requests": 25},
    {"country": "China", "requests": 12}
  ],
  "suspicious_ips": [
    {"ip": "192.168.1.105", "failed_attempts": 12}
  ]
}

GET /api/user

Get current authenticated user information.

Public Endpoints

GET /api/health

Health check endpoint (no authentication required).

Response:

{
  "status": "OK",
  "service": "SecuScan Backend"
}

πŸ“Š Sample Log Format

Security logs are parsed from server/security.log:

timestamp|ip_address|event_type|status|details
2024-01-19 08:15:23|192.168.1.105|Failed Login|failed|Invalid password attempt
2024-01-19 09:10:15|203.45.123.89|SQL Injection Attempt|blocked|union select from users...

πŸ› οΈ Development

Tech Stack

Frontend:

  • React 18.2 - UI library
  • Vite 5.0 - Build tool (instant HMR)
  • Recharts 2.10 - Data visualization
  • Axios 1.6 - HTTP client
  • CSS3 - Styling with gradients and animations

Backend:

  • Flask 3.0 - Web framework
  • PyJWT 2.8 - JWT authentication
  • Flask-CORS 4.0 - CORS handling
  • Python 3.8+ - Runtime

Environment Variables

Create .env file in server/ (optional):

SECRET_KEY=your-super-secret-key-change-this
FLASK_ENV=production
FLASK_DEBUG=False

Adding New Features

  1. New API Endpoint:

    @app.route('/api/new-endpoint', methods=['GET'])
    @token_required
    def new_endpoint(current_user):
        return jsonify({'data': 'value'}), 200
  2. New Detection Pattern:

    new_pattern = r'your-regex-pattern'
    # Add to _calculate_severity() method
  3. New Chart:

    // In Dashboard.jsx
    <div className="chart-card">
      <h2>New Chart Title</h2>
      <ResponsiveContainer width="100%" height={300}>
        {/* Add Recharts component */}
      </ResponsiveContainer>
    </div>

πŸ”’ Security Best Practices Implemented

Practice Implementation Benefit
Authentication JWT tokens with expiration Prevents unauthorized access
Password Hashing Credentials validated server-side Protects against credential theft
HTTPS Ready Can add SSL/TLS in production Encrypts data in transit
CORS Flask-CORS configured Prevents cross-origin attacks
Input Validation Sanitize all user inputs Prevents injection attacks
Request Limits 1MB max payload Prevents DoS attacks
Error Handling Generic error messages Prevents information disclosure
Rate Limiting Ready for integration Prevents brute force attacks
Pattern Detection Regex-based threat analysis Detects known attack patterns

πŸ“ˆ Why This Project Stands Out on Your CV

Demonstrates Cybersecurity Knowledge

βœ… Implements JWT authentication (not just basic auth)
βœ… Detects real attack patterns (SQL injection, path traversal)
βœ… Understands intrusion detection methodology
βœ… Knows security logging best practices

Shows Full-Stack Development

βœ… Frontend: React with modern tooling (Vite)
βœ… Backend: Python (king of cybersecurity)
βœ… DevOps: Monorepo with single npm start
βœ… Database: Log parsing and analysis

Proves Code Quality

βœ… Well-documented security features
βœ… Clean, modular code structure
βœ… Error handling and validation
βœ… RESTful API design

Interview Talking Points

  • "I implemented JWT authentication with 24-hour token expiration"
  • "The analyzer detects multiple attack patterns including SQL injection and path traversal"
  • "Set up a monorepo architecture with concurrent processes running"
  • "Built a data visualization dashboard with Recharts for security metrics"
  • "Implemented request size limiting to prevent DoS attacks"

🚒 Deployment

Production Checklist

# 1. Update secret key
export SECRET_KEY=generate-strong-random-key

# 2. Disable debug mode (already set to False)

# 3. Use production CORS settings
CORS(app, origins=['https://yourdomain.com'])

# 4. Add SSL/TLS certificates
# Configure in web server (Nginx, Apache)

# 5. Set up environment variables
export FLASK_ENV=production
export DEBUG=False

# 6. Use production server (Gunicorn)
pip install gunicorn
gunicorn -w 4 -b 0.0.0.0:5000 main:app

# 7. Use npm production build
npm run build

# 8. Serve with web server
# Configure Nginx to serve static files and proxy API

Docker Deployment (Optional)

# Backend Dockerfile
FROM python:3.11-slim
WORKDIR /app
COPY requirements.txt .
RUN pip install -r requirements.txt
COPY . .
CMD ["gunicorn", "-w", "4", "-b", "0.0.0.0:5000", "main:app"]

# Frontend is built to static files and served by Nginx

πŸ“ License

This project is provided as an educational resource for your portfolio and CV.

🀝 Contributing

This is a personal portfolio project. Feel free to extend with:

  • Real GeoIP database integration
  • Database storage (PostgreSQL, MongoDB)
  • Real-time WebSocket updates
  • Machine learning threat detection
  • User roles and RBAC
  • 2FA authentication
  • Audit logging

πŸ“§ Questions?

For implementation details on security features, refer to comments in:

  • server/main.py - Security middleware and endpoint protection
  • server/main.py - Threat pattern detection logic
  • client/src/App.jsx - JWT token handling

Built with ❀️ to demonstrate cybersecurity expertise

About

Full-stack security dashboard with log analysis, intrusion detection, and JWT authentication.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

No releases published

Packages

 
 
 

Contributors