Elysia Tools

在一个清晰的工作台里浏览工具、案例、可视化和主题指南。

热门分类

专题

语言
ZHDERUPTENFRES

Elysia Tools

导航

安全

网络安全和SSL/TLS配置

全面的网络安全示例,包括SSL/TLS配置、防火墙规则、VPN设置和网络扫描防护

案例

这个案例集合中的条目

代码text中等

SSL/TLS配置和证书管理

Web服务器的完整SSL/TLS设置,包含证书生成、HTTPS配置和安全最佳实践

难度

6/10

预计时间

25 min

标签

ssl, tls, nginx, https, certificates

前置条件

Linux administration, Nginx/Apache basics, SSL/TLS concepts

text
# SSL/TLS Configuration for Nginx
# This file provides a comprehensive SSL/TLS setup for web servers

# Generate Self-Signed Certificate (for development)
# openssl req -x509 -nodes -days 365 -newkey rsa:2048 \
#     -keyout /etc/nginx/ssl/private/nginx-selfsigned.key \
#     -out /etc/nginx/ssl/certs/nginx-selfsigned.crt \
#     -subj "/C=US/ST=California/L=San Francisco/O=Example/CN=localhost"

# Generate DH Parameters for Perfect Forward Secrecy
# openssl dhparam -out /etc/nginx/ssl/dhparam.pem 2048

server {
    listen 80;
    server_name example.com www.example.com;

    # Redirect all HTTP traffic to HTTPS
    return 301 https://$server_name$request_uri;
}

server {
    listen 443 ssl http2;
    server_name example.com www.example.com;

    # SSL Configuration
    ssl_certificate /etc/nginx/ssl/certs/nginx-selfsigned.crt;
    ssl_certificate_key /etc/nginx/ssl/private/nginx-selfsigned.key;

    # Perfect Forward Secrecy
    ssl_dhparam /etc/nginx/ssl/dhparam.pem;

    # SSL Protocols - Disable weak protocols
    ssl_protocols TLSv1.2 TLSv1.3;
    ssl_prefer_server_ciphers on;

    # Strong Cipher Suites
    ssl_ciphers 'ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-CHACHA20-POLY1305:ECDHE-RSA-CHACHA20-POLY1305:DHE-RSA-AES128-GCM-SHA256:DHE-RSA-AES256-GCM-SHA384';

    # SSL Session Configuration
    ssl_session_timeout 1d;
    ssl_session_cache shared:SSL:50m;
    ssl_session_tickets off;

    # OCSP Stapling
    ssl_stapling on;
    ssl_stapling_verify on;
    resolver 8.8.8.8 8.8.4.4 valid=300s;
    resolver_timeout 5s;

    # HSTS (HTTP Strict Transport Security)
    add_header Strict-Transport-Security "max-age=63072000; includeSubDomains; preload" always;

    # Other Security Headers
    add_header X-Frame-Options DENY;
    add_header X-Content-Type-Options nosniff;
    add_header X-XSS-Protection "1; mode=block";
    add_header Referrer-Policy "strict-origin-when-cross-origin";

    # Content Security Policy
    add_header Content-Security-Policy "default-src 'self'; http-src 'self' https: data: blob: 'unsafe-inline'";

    # Root directory
    root /var/www/html;
    index index.html index.htm;

    # Main location block
    location / {
        try_files $uri $uri/ =404;
    }

    # Security: Hide server version
    server_tokens off;

    # Security: Limit request methods
    if ($request_method !~ ^(GET|HEAD|POST)$ ) {
        return 405;
    }

    # Security: Prevent access to hidden files
    location ~ /\. {
        deny all;
        access_log off;
        log_not_found off;
    }

    # Security: Prevent access to backup files
    location ~ ~$ {
        deny all;
        access_log off;
        log_not_found off;
    }

    # Rate limiting
    limit_req_zone $binary_remote_addr zone=api:10m rate=10r/s;

    location /api/ {
        limit_req zone=api burst=20 nodelay;
        proxy_pass http://backend;
    }
}

# Apache SSL/TLS Configuration (alternative)
# File: /etc/apache2/sites-available/default-ssl.conf

<IfModule mod_ssl.c>
    <VirtualHost _default_:443>
        ServerAdmin webmaster@localhost
        DocumentRoot /var/www/html

        # SSL Configuration
        SSLEngine on
        SSLCertificateFile /etc/ssl/certs/ssl-cert-snakeoil.pem
        SSLCertificateKeyFile /etc/ssl/private/ssl-cert-snakeoil.key

        # SSL Protocol Configuration
        SSLProtocol all -SSLv3 -TLSv1 -TLSv1.1
        SSLCipherSuite HIGH:!aNULL:!MD5
        SSLHonorCipherOrder on

        # SSL Session Configuration
        SSLSessionCache shmcb:/var/run/apache2/ssl_scache(512000)
        SSLSessionCacheTimeout 300

        # Security Headers
        Header always set Strict-Transport-Security "max-age=63072000; includeSubDomains; preload"
        Header always set X-Frame-Options DENY
        Header always set X-Content-Type-Options nosniff
        Header always set X-XSS-Protection "1; mode=block"
        Header always set Referrer-Policy "strict-origin-when-cross-origin"

        # HSTS
        Header always set Strict-Transport-Security "max-age=63072000; includeSubDomains; preload"

        # OCSP Stapling
        SSLUseStapling on
        SSLStaplingResponderTimeout 5
        SSLStaplingReturnResponderErrors off
        SSLStaplingCache shmcb:/var/run/ocsp(128000)

        ErrorLog ${APACHE_LOG_DIR}/error.log
        CustomLog ${APACHE_LOG_DIR}/ssl_access.log combined
    </VirtualHost>
</IfModule>

# Let's Encrypt Certificate Setup Script
#!/bin/bash
# File: setup-letsencrypt.sh

set -e

DOMAIN="example.com"
EMAIL="admin@example.com"

# Install Certbot
sudo apt update
sudo apt install -y certbot python3-certbot-nginx

# Obtain SSL Certificate
sudo certbot --nginx -d $DOMAIN -d www.$DOMAIN --email $EMAIL --agree-tos --no-eff-email --redirect

# Setup auto-renewal
echo "0 12 * * * /usr/bin/certbot renew --quiet" | sudo crontab -

# Test renewal
sudo certbot renew --dry-run

echo "SSL Certificate setup completed for $DOMAIN"

# SSL Configuration Testing Script
#!/bin/bash
# File: test-ssl-configuration.sh

DOMAIN="example.com"

echo "Testing SSL Configuration for $DOMAIN"
echo "=================================="

# Test SSL/TLS Configuration
echo "1. SSL Configuration Test:"
openssl s_client -connect $DOMAIN:443 -servername $DOMAIN < /dev/null 2>/dev/null | openssl x509 -noout -dates

# Test SSL Protocols
echo -e "\n2. SSL Protocols Support:"
for protocol in sslv2 sslv3 tls1 tls1_1 tls1_2 tls1_3; do
    result=$(echo | openssl s_client -connect $DOMAIN:443 -$protocol 2>/dev/null | grep "Protocol.*$protocol")
    if [[ -n "$result" ]]; then
        echo "   ✓ $protocol: Supported"
    else
        echo "   ✗ $protocol: Not supported"
    fi
done

# Test SSL Labs Rating
echo -e "\n3. SSL Labs Test:"
echo "Visit: https://www.ssllabs.com/ssltest/analyze.html?d=$DOMAIN&hideResults=on"

# Test Certificate Chain
echo -e "\n4. Certificate Chain Test:"
openssl s_client -connect $DOMAIN:443 -showcerts < /dev/null 2>/dev/null | grep -E "(issuer|subject)"

# Test HTTPS Redirection
echo -e "\n5. HTTP to HTTPS Redirection:"
http_code=$(curl -s -o /dev/null -w "%{http_code}" http://$DOMAIN)
if [[ "$http_code" == "301" ]] || [[ "$http_code" == "302" ]]; then
    echo "   ✓ HTTP redirects to HTTPS ($http_code)"
else
    echo "   ✗ HTTP does not redirect to HTTPS ($http_code)"
fi

# Test Security Headers
echo -e "\n6. Security Headers Test:"
curl -s -I https://$DOMAIN | grep -E "(Strict-Transport-Security|X-Frame-Options|X-Content-Type-Options|X-XSS-Protection)"

echo -e "\nSSL Configuration Test Complete"
代码shell中等

防火墙配置和网络保护

使用iptables、UFW和pfSense的综合防火墙设置,包含Web服务器保护、数据库防护和DDoS缓解

难度

7/10

预计时间

30 min

标签

firewall, iptables, ufw, network-security

前置条件

Linux administration, Network security basics

shell
#!/bin/bash
# Comprehensive Firewall Configuration Script
# Supports both iptables and UFW (Ubuntu/Debian)

set -e

# Configuration variables
WEB_SERVER_IP="192.168.1.100"
DB_SERVER_IP="192.168.1.200"
ALLOWED_SSH_IPS=("192.168.1.50" "203.0.113.100")
WEB_PORTS=("80" "443")
DB_PORTS=("3306" "5432" "6379")
SSH_PORT="22"

# Function to detect firewall system
detect_firewall_system() {
    if command -v ufw >/dev/null 2>&1; then
        echo "ufw"
    elif command -v firewall-cmd >/dev/null 2>&1; then
        echo "firewalld"
    else
        echo "iptables"
    fi
}

# UFW Configuration
setup_ufw() {
    echo "Setting up UFW (Uncomplicated Firewall)..."

    # Reset UFW to default state
    sudo ufw --force reset

    # Default policies
    sudo ufw default deny incoming
    sudo ufw default allow outgoing

    # Allow SSH from specific IPs
    for ip in "${ALLOWED_SSH_IPS[@]}"; do
        sudo ufw allow from $ip to any port $SSH_PORT proto tcp
        echo "Allowed SSH from $ip"
    done

    # Allow HTTP/HTTPS from anywhere
    for port in "${WEB_PORTS[@]}"; do
        sudo ufw allow $port/tcp
        echo "Allowed port $port (web traffic)"
    done

    # Rate limiting for SSH
    sudo ufw limit $SSH_PORT/tcp

    # Protection against common attacks
    sudo ufw deny 137:139/udp  # NetBIOS
    sudo ufw deny 445/tcp       # SMB

    # Enable logging
    sudo ufw logging on

    # Enable firewall
    sudo ufw --force enable

    echo "UFW configuration completed"
    sudo ufw status verbose
}

# iptables Configuration
setup_iptables() {
    echo "Setting up iptables..."

    # Flush existing rules
    sudo iptables -F
    sudo iptables -X
    sudo iptables -t nat -F
    sudo iptables -t nat -X
    sudo iptables -t mangle -F
    sudo iptables -t mangle -X

    # Set default policies
    sudo iptables -P INPUT DROP
    sudo iptables -P FORWARD DROP
    sudo iptables -P OUTPUT ACCEPT

    # Allow loopback
    sudo iptables -A INPUT -i lo -j ACCEPT
    sudo iptables -A OUTPUT -o lo -j ACCEPT

    # Allow established and related connections
    sudo iptables -A INPUT -m conntrack --ctstate ESTABLISHED,RELATED -j ACCEPT

    # Allow SSH from specific IPs
    for ip in "${ALLOWED_SSH_IPS[@]}"; do
        sudo iptables -A INPUT -p tcp -s $ip --dport $SSH_PORT -m conntrack --ctstate NEW,ESTABLISHED -j ACCEPT
        echo "Allowed SSH from $ip"
    done

    # Allow HTTP/HTTPS
    for port in "${WEB_PORTS[@]}"; do
        sudo iptables -A INPUT -p tcp --dport $port -m conntrack --ctstate NEW,ESTABLISHED -j ACCEPT
        echo "Allowed port $port"
    done

    # Rate limiting for SSH
    sudo iptables -A INPUT -p tcp --dport $SSH_PORT -m conntrack --ctstate NEW -m recent --set
    sudo iptables -A INPUT -p tcp --dport $SSH_PORT -m conntrack --ctstate NEW -m recent --update --seconds 60 --hitcount 4 -j DROP

    # Protection against common attacks
    # Block null packets
    sudo iptables -A INPUT -p tcp --tcp-flags ALL NONE -j DROP

    # Block syn-flood attacks
    sudo iptables -A INPUT -p tcp ! --syn -m state --state NEW -j DROP
    sudo iptables -A INPUT -p tcp --tcp-flags ALL ALL -m limit --limit 1/s --limit-burst 3 -j ACCEPT

    # Block XMAS packets
    sudo iptables -A INPUT -p tcp --tcp-flags ALL ALL -j DROP

    # Block malformed packets
    sudo iptables -A INPUT -m conntrack --ctstate INVALID -j DROP

    # Ping of death protection
    sudo iptables -A INPUT -p icmp --icmp-type echo-request -m limit --limit 1/s --limit-burst 3 -j ACCEPT
    sudo iptables -A INPUT -p icmp --icmp-type echo-request -j DROP

    # Protection against port scanning
    sudo iptables -A INPUT -m recent --name portscan --rcheck --seconds 86400 -j DROP
    sudo iptables -A INPUT -m recent --name portscan --set -j LOG --log-prefix "Portscan:"
    sudo iptables -A INPUT -m recent --name portscan --set -j DROP

    # Save rules
    if command -v iptables-save >/dev/null 2>&1; then
        sudo iptables-save > /etc/iptables/rules.v4
        echo "iptables rules saved to /etc/iptables/rules.v4"
    fi

    echo "iptables configuration completed"
    sudo iptables -L -n -v
}

# firewalld Configuration (CentOS/RHEL)
setup_firewalld() {
    echo "Setting up firewalld..."

    # Start and enable firewalld
    sudo systemctl start firewalld
    sudo systemctl enable firewalld

    # Set default zone
    sudo firewall-cmd --set-default-zone=public

    # Allow SSH from specific IPs
    for ip in "${ALLOWED_SSH_IPS[@]}"; do
        sudo firewall-cmd --permanent --zone=public --add-rich-rule="rule family='ipv4' source address='$ip' service name='ssh' accept"
        echo "Allowed SSH from $ip"
    done

    # Allow HTTP/HTTPS
    sudo firewall-cmd --permanent --zone=public --add-service=http
    sudo firewall-cmd --permanent --zone=public --add-service=https
    echo "Allowed HTTP/HTTPS services"

    # Rate limiting for SSH
    sudo firewall-cmd --permanent --zone=public --add-rich-rule="rule service name='ssh' limit value='4/m' accept"

    # Block suspicious traffic
    sudo firewall-cmd --permanent --zone=public --add-service=samba
    sudo firewall-cmd --permanent --zone=public --remove-service=samba

    # Reload firewalld
    sudo firewall-cmd --reload

    echo "firewalld configuration completed"
    sudo firewall-cmd --list-all
}

# Docker Firewall Rules
setup_docker_rules() {
    echo "Setting up Docker firewall rules..."

    # Allow Docker container traffic
    sudo iptables -I DOCKER-USER -i docker0 -j ACCEPT
    sudo iptables -I DOCKER-USER -o docker0 -j ACCEPT

    # Allow established connections from containers
    sudo iptables -I DOCKER-USER -m conntrack --ctstate ESTABLISHED,RELATED -j ACCEPT

    # Prevent containers from accessing critical services
    sudo iptables -I DOCKER-USER -p tcp --dport 22 -j DROP   # SSH
    sudo iptables -I DOCKER-USER -p tcp --dport 3306 -j DROP # MySQL

    echo "Docker firewall rules configured"
}

# Fail2ban Configuration
setup_fail2ban() {
    echo "Setting up Fail2ban..."

    # Install Fail2ban
    if command -v apt >/dev/null 2>&1; then
        sudo apt update && sudo apt install -y fail2ban
    elif command -v yum >/dev/null 2>&1; then
        sudo yum install -y epel-release
        sudo yum install -y fail2ban
    fi

    # Create Fail2ban configuration
    sudo tee /etc/fail2ban/jail.local > /dev/null <<EOF
[DEFAULT]
bantime = 3600
findtime = 600
maxretry = 3
backend = systemd

[sshd]
enabled = true
port = $SSH_PORT
filter = sshd
logpath = /var/log/auth.log
maxretry = 3
bantime = 3600

[nginx-http-auth]
enabled = true
filter = nginx-http-auth
logpath = /var/log/nginx/error.log
maxretry = 3
bantime = 3600

[nginx-limit-req]
enabled = true
filter = nginx-limit-req
logpath = /var/log/nginx/error.log
maxretry = 5
bantime = 600

[nginx-botsearch]
enabled = true
filter = nginx-botsearch
logpath = /var/log/nginx/access.log
maxretry = 2
bantime = 86400
EOF

    # Start and enable Fail2ban
    sudo systemctl restart fail2ban
    sudo systemctl enable fail2ban

    echo "Fail2ban configuration completed"
    sudo fail2ban-client status
}

# DDoS Protection Rules
setup_ddos_protection() {
    echo "Setting up DDoS protection..."

    # Connection limiting
    sudo iptables -A INPUT -p tcp --dport 80 -m connlimit --connlimit-above 100 -j REJECT
    sudo iptables -A INPUT -p tcp --dport 443 -m connlimit --connlimit-above 100 -j REJECT

    # SYN flood protection
    sudo iptables -N SYN_FLOOD
    sudo iptables -A SYN_FLOOD -m limit --limit 1/s --limit-burst 3 -j RETURN
    sudo iptables -A SYN_FLOOD -j DROP

    sudo iptables -A INPUT -p tcp --syn -j SYN_FLOOD

    # HTTP DDoS protection
    sudo iptables -A INPUT -p tcp --dport 80 -m conntrack --ctstate NEW -m recent --set
    sudo iptables -A INPUT -p tcp --dport 80 -m conntrack --ctstate NEW -m recent --update --seconds 1 --hitcount 30 -j DROP

    sudo iptables -A INPUT -p tcp --dport 443 -m conntrack --ctstate NEW -m recent --set
    sudo iptables -A INPUT -p tcp --dport 443 -m conntrack --ctstate NEW -m recent --update --seconds 1 --hitcount 30 -j DROP

    echo "DDoS protection rules configured"
}

# Monitoring and Logging
setup_monitoring() {
    echo "Setting up monitoring and logging..."

    # Enable connection tracking logging
    sudo iptables -A INPUT -m conntrack --ctstate NEW -j LOG --log-prefix "NEW-CONN: " --log-level 4

    # Create log directory
    sudo mkdir -p /var/log/firewall

    # Setup log rotation for firewall logs
    sudo tee /etc/logrotate.d/firewall > /dev/null <<EOF
/var/log/firewall/*.log {
    daily
    rotate 7
    compress
    delaycompress
    missingok
    notifempty
    create 644 root root
}
EOF

    echo "Firewall monitoring configured"
}

# Main execution
main() {
    echo "Starting firewall configuration..."
    echo "================================"

    # Check if running as root
    if [[ $EUID -ne 0 ]]; then
        echo "This script must be run as root"
        exit 1
    fi

    # Detect firewall system
    firewall_system=$(detect_firewall_system)
    echo "Detected firewall system: $firewall_system"

    # Setup appropriate firewall
    case $firewall_system in
        "ufw")
            setup_ufw
            ;;
        "firewalld")
            setup_firewalld
            ;;
        *)
            setup_iptables
            ;;
    esac

    # Setup additional security measures
    setup_docker_rules
    setup_fail2ban
    setup_ddos_protection
    setup_monitoring

    echo "Firewall configuration completed successfully!"
    echo "Remember to test your configuration before deploying to production."
}

# Run main function
main "$@"
代码shell复杂

WireGuard VPN设置

使用WireGuard进行安全站点间和远程访问连接的完整VPN服务器和客户端配置

难度

8/10

预计时间

35 min

标签

vpn, wireguard, network-security, tunnel

前置条件

Linux administration, Network fundamentals, Firewall configuration

shell
#!/bin/bash
# WireGuard VPN Server Setup Script
# Supports both Ubuntu/Debian and CentOS/RHEL

set -e

# Configuration variables
VPN_SERVER_IP="10.8.0.1"
VPN_NETWORK="10.8.0.0/24"
VPN_PORT="51820"
SERVER_EXTERNAL_IP=$(curl -s ifconfig.me)
SERVER_INTERFACE="wg0"

# Colors for output
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m' # No Color

log() {
    echo -e "${GREEN}[$(date '+%Y-%m-%d %H:%M:%S')] $1${NC}"
}

warn() {
    echo -e "${YELLOW}[$(date '+%Y-%m-%d %H:%M:%S')] WARNING: $1${NC}"
}

error() {
    echo -e "${RED}[$(date '+%Y-%m-%d %H:%M:%S')] ERROR: $1${NC}"
}

# Install WireGuard
install_wireguard() {
    log "Installing WireGuard..."

    if command -v apt >/dev/null 2>&1; then
        # Ubuntu/Debian
        sudo apt update
        sudo apt install -y wireguard wireguard-tools qrencode

        # Enable IP forwarding
        sudo sysctl -w net.ipv4.ip_forward=1
        echo "net.ipv4.ip_forward=1" | sudo tee /etc/sysctl.d/99-wireguard.conf

        # Install resolvconf for DNS management
        sudo apt install -y resolvconf

    elif command -v yum >/dev/null 2>&1; then
        # CentOS/RHEL
        sudo yum install -y epel-release
        sudo yum install -y wireguard-tools qrencode

        # Enable IP forwarding
        sudo sysctl -w net.ipv4.ip_forward=1
        echo "net.ipv4.ip_forward=1" | sudo tee /etc/sysctl.d/99-wireguard.conf

        # Install resolvconf for DNS management
        sudo yum install -y resolvconf
    else
        error "Unsupported operating system"
        exit 1
    fi

    log "WireGuard installed successfully"
}

# Generate server and client keys
generate_keys() {
    log "Generating cryptographic keys..."

    # Create directory for keys
    sudo mkdir -p /etc/wireguard/clients

    # Generate server keys
    sudo wg genkey | sudo tee /etc/wireguard/private.key | sudo wg pubkey | sudo tee /etc/wireguard/public.key

    # Set proper permissions
    sudo chmod 600 /etc/wireguard/private.key
    sudo chmod 644 /etc/wireguard/public.key

    # Read server keys
    SERVER_PRIVATE_KEY=$(sudo cat /etc/wireguard/private.key)
    SERVER_PUBLIC_KEY=$(sudo cat /etc/wireguard/public.key)

    log "Server keys generated"
    log "Server Public Key: $SERVER_PUBLIC_KEY"
}

# Configure WireGuard interface
configure_server() {
    log "Configuring WireGuard server..."

    # Create server configuration
    sudo tee /etc/wireguard/$SERVER_INTERFACE.conf > /dev/null <<EOF
[Interface]
Address = $VPN_SERVER_IP/24
ListenPort = $VPN_PORT
PrivateKey = $SERVER_PRIVATE_KEY

# DNS configuration for clients
DNS = 1.1.1.1, 8.8.8.8

# Enable connection tracking
PostUp = iptables -A FORWARD -i $SERVER_INTERFACE -j ACCEPT; iptables -t nat -A POSTROUTING -o $(ip route get 8.8.8.8 | awk '{print $5}') -j MASQUERADE; iptables -A INPUT -p udp --dport $VPN_PORT -j ACCEPT
PostDown = iptables -D FORWARD -i $SERVER_INTERFACE -j ACCEPT; iptables -t nat -D POSTROUTING -o $(ip route get 8.8.8.8 | awk '{print $5}') -j MASQUERADE; iptables -D INPUT -p udp --dport $VPN_PORT -j ACCEPT

# Performance tuning
Table = off
SaveConfig = true
EOF

    log "Server configuration created"
}

# Create client configuration template
create_client_template() {
    local client_name="$1"
    local client_ip="$2"

    log "Creating client configuration for $client_name..."

    # Generate client keys
    sudo wg genkey | sudo tee /etc/wireguard/clients/${client_name}_private.key | sudo wg pubkey | sudo tee /etc/wireguard/clients/${client_name}_public.key

    # Read client keys
    CLIENT_PRIVATE_KEY=$(sudo cat /etc/wireguard/clients/${client_name}_private.key)
    CLIENT_PUBLIC_KEY=$(sudo cat /etc/wireguard/clients/${client_name}_public.key)

    # Create client configuration
    sudo tee /etc/wireguard/clients/${client_name}.conf > /dev/null <<EOF
[Interface]
PrivateKey = $CLIENT_PRIVATE_KEY
Address = $client_ip/24
DNS = 1.1.1.1, 8.8.8.8

[Peer]
PublicKey = $SERVER_PUBLIC_KEY
Endpoint = $SERVER_EXTERNAL_IP:$VPN_PORT
AllowedIPs = 0.0.0.0/0, ::/0
PersistentKeepalive = 25
EOF

    # Add client to server configuration
    sudo tee -a /etc/wireguard/$SERVER_INTERFACE.conf > /dev/null <<EOF

# Peer: $client_name
[Peer]
PublicKey = $CLIENT_PUBLIC_KEY
AllowedIPs = $client_ip/32
EOF

    # Generate QR code for mobile clients
    sudo qrencode -t png -o /etc/wireguard/clients/${client_name}.png < /etc/wireguard/clients/${client_name}.conf

    # Set permissions
    sudo chmod 600 /etc/wireguard/clients/${client_name}_private.key
    sudo chmod 644 /etc/wireguard/clients/${client_name}.conf
    sudo chmod 644 /etc/wireguard/clients/${client_name}_public.key

    log "Client $client_name configured with IP: $client_ip"
    log "Client Public Key: $CLIENT_PUBLIC_KEY"
    log "QR Code generated: /etc/wireguard/clients/${client_name}.png"
}

# Create firewall rules for WireGuard
setup_firewall() {
    log "Setting up firewall rules for WireGuard..."

    # Allow WireGuard traffic
    if command -v ufw >/dev/null 2>&1; then
        sudo ufw allow $VPN_PORT/udp
        log "Allowed WireGuard port $VPN_PORT/udp through UFW"
    elif command -v firewall-cmd >/dev/null 2>&1; then
        sudo firewall-cmd --permanent --add-port=$VPN_PORT/udp
        sudo firewall-cmd --reload
        log "Allowed WireGuard port $VPN_PORT/udp through firewalld"
    else
        # iptables rules
        sudo iptables -A INPUT -p udp --dport $VPN_PORT -j ACCEPT
        sudo iptables -A INPUT -i $SERVER_INTERFACE -j ACCEPT
        sudo iptables -A FORWARD -i $SERVER_INTERFACE -j ACCEPT

        # NAT for outgoing traffic
        sudo iptables -t nat -A POSTROUTING -s $VPN_NETWORK -o $(ip route get 8.8.8.8 | awk '{print $5}') -j MASQUERADE

        log "WireGuard iptables rules configured"
    fi
}

# Start WireGuard service
start_wireguard() {
    log "Starting WireGuard service..."

    # Enable and start WireGuard
    sudo systemctl enable wg-quick@$SERVER_INTERFACE
    sudo systemctl start wg-quick@$SERVER_INTERFACE

    # Check status
    sudo systemctl status wg-quick@$SERVER_INTERFACE --no-pager

    # Show interface status
    sudo wg show
}

# Create management scripts
create_management_scripts() {
    log "Creating management scripts..."

    # Create add client script
    sudo tee /usr/local/bin/wg-add-client > /dev/null <<'EOF'
#!/bin/bash

if [[ $# -ne 1 ]]; then
    echo "Usage: wg-add-client <client-name>"
    exit 1
fi

CLIENT_NAME="$1"
VPN_SERVER_IP="10.8.0.1"
SERVER_PUBLIC_KEY=$(sudo cat /etc/wireguard/public.key)

# Find next available IP
LAST_IP=$(sudo grep -o "AllowedIPs = 10\.8\.0\.[0-9]*" /etc/wireguard/wg0.conf | tail -1 | grep -o "[0-9]*$" | head -1)
NEXT_IP=$((LAST_IP + 1))

if [[ -z "$LAST_IP" ]]; then
    NEXT_IP=2
fi

CLIENT_IP="10.8.0.$NEXT_IP"

# Generate client keys
sudo wg genkey | sudo tee /etc/wireguard/clients/${CLIENT_NAME}_private.key | sudo wg pubkey | sudo tee /etc/wireguard/clients/${CLIENT_NAME}_public.key

CLIENT_PRIVATE_KEY=$(sudo cat /etc/wireguard/clients/${CLIENT_NAME}_private.key)
CLIENT_PUBLIC_KEY=$(sudo cat /etc/wireguard/clients/${CLIENT_NAME}_public.key)

# Create client configuration
sudo tee /etc/wireguard/clients/${CLIENT_NAME}.conf > /dev/null <<EOCONF
[Interface]
PrivateKey = $CLIENT_PRIVATE_KEY
Address = $CLIENT_IP/24
DNS = 1.1.1.1, 8.8.8.8

[Peer]
PublicKey = $SERVER_PUBLIC_KEY
Endpoint = $(curl -s ifconfig.me):51820
AllowedIPs = 0.0.0.0/0, ::/0
PersistentKeepalive = 25
EOCONF

# Add peer to server configuration
sudo tee -a /etc/wireguard/wg0.conf > /dev/null <<EOCONF

# Peer: $CLIENT_NAME
[Peer]
PublicKey = $CLIENT_PUBLIC_KEY
AllowedIPs = $CLIENT_IP/32
EOCONF

# Generate QR code
sudo qrencode -t png -o /etc/wireguard/clients/${CLIENT_NAME}.png < /etc/wireguard/clients/${CLIENT_NAME}.conf

echo "Client $CLIENT_NAME added with IP: $CLIENT_IP"
echo "Configuration: /etc/wireguard/clients/${CLIENT_NAME}.conf"
echo "QR Code: /etc/wireguard/clients/${CLIENT_NAME}.png"

# Reload WireGuard
sudo systemctl restart wg-quick@wg0
EOF

    # Create list clients script
    sudo tee /usr/local/bin/wg-list-clients > /dev/null <<'EOF'
#!/bin/bash

echo "WireGuard VPN Clients:"
echo "====================="

sudo wg show wg0 peers

echo -e "\nClient Configurations:"
for client_conf in /etc/wireguard/clients/*.conf; do
    if [[ -f "$client_conf" ]]; then
        client_name=$(basename "$client_conf" .conf)
        client_ip=$(grep "Address = " "$client_conf" | cut -d' ' -f3)
        echo "$client_name: $client_ip"
    fi
done
EOF

    # Create remove client script
    sudo tee /usr/local/bin/wg-remove-client > /dev/null <<'EOF'
#!/bin/bash

if [[ $# -ne 1 ]]; then
    echo "Usage: wg-remove-client <client-name>"
    exit 1
fi

CLIENT_NAME="$1"

# Backup current configuration
sudo cp /etc/wireguard/wg0.conf /etc/wireguard/wg0.conf.bak

# Remove peer from server configuration
sudo sed -i "/# Peer: $CLIENT_NAME/,/^$/d" /etc/wireguard/wg0.conf

# Remove client files
sudo rm -f /etc/wireguard/clients/${CLIENT_NAME}_private.key
sudo rm -f /etc/wireguard/clients/${CLIENT_NAME}_public.key
sudo rm -f /etc/wireguard/clients/${CLIENT_NAME}.conf
sudo rm -f /etc/wireguard/clients/${CLIENT_NAME}.png

echo "Client $CLIENT_NAME removed"

# Reload WireGuard
sudo systemctl restart wg-quick@wg0
EOF

    # Make scripts executable
    sudo chmod +x /usr/local/bin/wg-add-client
    sudo chmod +x /usr/local/bin/wg-list-clients
    sudo chmod +x /usr/local/bin/wg-remove-client

    log "Management scripts created"
}

# Setup monitoring and logging
setup_monitoring() {
    log "Setting up monitoring and logging..."

    # Create log directory
    sudo mkdir -p /var/log/wireguard

    # Configure log rotation
    sudo tee /etc/logrotate.d/wireguard > /dev/null <<EOF
/var/log/wireguard/*.log {
    daily
    rotate 7
    compress
    delaycompress
    missingok
    notifempty
    create 644 root root
}
EOF

    # Create status monitoring script
    sudo tee /usr/local/bin/wg-status > /dev/null <<'EOF'
#!/bin/bash

echo "WireGuard VPN Status"
echo "===================="

# Check if service is running
if systemctl is-active --quiet wg-quick@wg0; then
    echo "✓ WireGuard service is running"
else
    echo "✗ WireGuard service is not running"
fi

# Show interface status
echo -e "\nInterface Status:"
sudo wg show

# Show connected peers
echo -e "\nConnected Peers:"
sudo wg show wg0 dump

# Show network routes
echo -e "\nNetwork Routes:"
ip route show | grep 10.8.0
EOF

    sudo chmod +x /usr/local/bin/wg-status

    log "Monitoring configured"
}

# Main installation function
main() {
    log "Starting WireGuard VPN server installation..."

    # Check if running as root
    if [[ $EUID -ne 0 ]]; then
        error "This script must be run as root"
        exit 1
    fi

    # Get server external IP
    SERVER_EXTERNAL_IP=$(curl -s ifconfig.me)
    log "Server external IP: $SERVER_EXTERNAL_IP"

    # Installation steps
    install_wireguard
    generate_keys
    configure_server

    # Create initial client
    create_client_template "laptop" "10.8.0.2"
    create_client_template "mobile" "10.8.0.3"

    setup_firewall
    setup_monitoring
    create_management_scripts

    # Start service
    start_wireguard

    log "WireGuard VPN server installation completed!"
    echo -e "\n${GREEN}VPN Server Details:${NC}"
    echo "Server IP: $SERVER_EXTERNAL_IP"
    echo "VPN Port: $VPN_PORT"
    echo "VPN Network: $VPN_NETWORK"

    echo -e "\n${GREEN}Client Configurations:${NC}"
    echo "Laptop: /etc/wireguard/clients/laptop.conf"
    echo "Mobile: /etc/wireguard/clients/mobile.conf"

    echo -e "\n${GREEN}Management Commands:${NC}"
    echo "Add client: wg-add-client <client-name>"
    echo "List clients: wg-list-clients"
    echo "Remove client: wg-remove-client <client-name>"
    echo "Show status: wg-status"

    warn "Remember to configure port forwarding on your router for port $VPN_PORT/UDP"
}

# Run main function
main "$@"
代码python复杂

网络扫描检测和保护

网络扫描检测系统实现,包含端口敲门和对侦察攻击的主动防御机制

难度

9/10

预计时间

40 min

标签

network-scanning, security, intrusion-detection, packet-analysis

前置条件

Python, Network security, Scapy, iptables

python
#!/usr/bin/env python3
"""
Network Scanning Detection and Protection System
Monitors network traffic for suspicious scanning activities and implements active defense measures
"""

import time
import socket
import threading
import subprocess
import re
import json
import logging
from datetime import datetime, timedelta
from collections import defaultdict, deque
from scapy.all import *
from scapy.layers.inet import IP, TCP, UDP, ICMP
from dataclasses import dataclass, asdict
from typing import Dict, List, Set, Tuple, Optional
import geoip2.database
import psutil

# Configuration
CONFIG = {
    'scan_detection_threshold': 20,      # Number of ports scanned before flagging
    'time_window': 60,                   # Time window in seconds
    'max_connections_per_ip': 50,       # Max connections from single IP
    'block_duration': 3600,             # Block duration in seconds (1 hour)
    'log_file': '/var/log/network_security.log',
    'iptables_chain': 'SCAN_PROTECTION',
    'port_knock_sequence': [7000, 8000, 9000],  # Port knock sequence
    'whitelist': [
        '127.0.0.1',
        '192.168.1.0/24',  # Local network
        '8.8.8.8',         # Google DNS
        '8.8.4.4',         # Google DNS
    ],
    'critical_ports': [22, 80, 443, 3306, 5432, 6379, 27017],
    'geoip_database': '/usr/share/GeoIP/GeoLite2-Country.mmdb'
}

@dataclass
class ScanEvent:
    timestamp: datetime
    source_ip: str
    scan_type: str
    ports_scanned: List[int]
    packet_count: int
    geo_location: Optional[str] = None

@dataclass
class ConnectionRecord:
    source_ip: str
    destination_port: int
    timestamp: datetime
    protocol: str
    flags: Optional[str] = None

class NetworkScanDetector:
    """Main network scanning detection system"""

    def __init__(self):
        self.scan_events = []
        self.connection_records = deque(maxlen=10000)
        self.blocked_ips = {}
        self.port_knock_attempts = defaultdict(list)
        self.scan_statistics = defaultdict(int)
        self.geoip_reader = None

        # Setup logging
        self.setup_logging()

        # Initialize GeoIP if available
        try:
            self.geoip_reader = geoip2.database.Reader(CONFIG['geoip_database'])
            self.logger.info("GeoIP database loaded successfully")
        except Exception as e:
            self.logger.warning(f"Could not load GeoIP database: {e}")

        # Setup iptables chain
        self.setup_iptables_chain()

        # Start monitoring threads
        self.start_monitoring()

    def setup_logging(self):
        """Setup logging configuration"""
        logging.basicConfig(
            level=logging.INFO,
            format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
            handlers=[
                logging.FileHandler(CONFIG['log_file']),
                logging.StreamHandler()
            ]
        )
        self.logger = logging.getLogger('NetworkSecurity')

    def setup_iptables_chain(self):
        """Setup iptables chain for blocking IPs"""
        try:
            # Create custom chain
            subprocess.run([
                'iptables', '-N', CONFIG['iptables_chain']
            ], check=False, stderr=subprocess.DEVNULL)

            # Create jump to custom chain
            subprocess.run([
                'iptables', '-I', 'INPUT', '1', '-j', CONFIG['iptables_chain']
            ], check=False)

            self.logger.info(f"iptables chain '{CONFIG['iptables_chain']}' setup complete")
        except Exception as e:
            self.logger.error(f"Failed to setup iptables chain: {e}")

    def is_whitelisted(self, ip: str) -> bool:
        """Check if IP is in whitelist"""
        for whitelist_entry in CONFIG['whitelist']:
            if '/' in whitelist_entry:
                # CIDR notation
                try:
                    import ipaddress
                    network = ipaddress.IPv4Network(whitelist_entry, strict=False)
                    addr = ipaddress.IPv4Address(ip)
                    if addr in network:
                        return True
                except:
                    pass
            else:
                if ip == whitelist_entry:
                    return True
        return False

    def get_geo_location(self, ip: str) -> str:
        """Get geographical location for IP"""
        if not self.geoip_reader:
            return "Unknown"

        try:
            response = self.geoip_reader.country(ip)
            return f"{response.country.name} ({response.country.iso_code})"
        except:
            return "Unknown"

    def detect_port_scan(self, connections: List[ConnectionRecord]) -> Optional[ScanEvent]:
        """Detect port scanning activity"""
        # Group connections by source IP
        ip_connections = defaultdict(list)
        for conn in connections:
            ip_connections[conn.source_ip].append(conn)

        # Check each IP for scanning behavior
        for source_ip, conns in ip_connections.items():
            if self.is_whitelisted(source_ip):
                continue

            # Check time window
            recent_conns = [
                conn for conn in conns
                if datetime.now() - conn.timestamp < timedelta(seconds=CONFIG['time_window'])
            ]

            if len(recent_conns) < CONFIG['scan_detection_threshold']:
                continue

            # Analyze scan pattern
            unique_ports = set(conn.destination_port for conn in recent_conns)
            protocols = set(conn.protocol for conn in recent_conns)

            scan_type = self.classify_scan_type(recent_conns, unique_ports, protocols)

            if scan_type:
                return ScanEvent(
                    timestamp=datetime.now(),
                    source_ip=source_ip,
                    scan_type=scan_type,
                    ports_scanned=list(unique_ports),
                    packet_count=len(recent_conns),
                    geo_location=self.get_geo_location(source_ip)
                )

        return None

    def classify_scan_type(self, connections: List[ConnectionRecord],
                          unique_ports: Set[int], protocols: Set[str]) -> str:
        """Classify the type of scan"""
        if len(unique_ports) == len(CONFIG['critical_ports']):
            return "Targeted Critical Port Scan"
        elif len(unique_ports) > 100:
            return "Comprehensive Port Scan"
        elif len(protocols) > 1:
            return "Multi-Protocol Scan"
        elif any(conn.destination_port in CONFIG['critical_ports'] for conn in connections):
            return "Critical Port Scan"
        elif len(unique_ports) > 50:
            return "Broad Port Scan"
        else:
            return "Limited Port Scan"

    def block_ip(self, ip: str, reason: str):
        """Block IP address using iptables"""
        if self.is_whitelisted(ip):
            self.logger.warning(f"Attempted to block whitelisted IP: {ip}")
            return

        try:
            # Add iptables rule
            subprocess.run([
                'iptables', '-A', CONFIG['iptables_chain'],
                '-s', ip, '-j', 'DROP'
            ], check=True)

            # Record block
            self.blocked_ips[ip] = {
                'timestamp': datetime.now(),
                'reason': reason,
                'duration': CONFIG['block_duration']
            }

            self.logger.warning(f"Blocked IP {ip} for reason: {reason}")

            # Schedule unblocking
            threading.Timer(
                CONFIG['block_duration'],
                self.unblock_ip,
                args=[ip]
            ).start()

        except Exception as e:
            self.logger.error(f"Failed to block IP {ip}: {e}")

    def unblock_ip(self, ip: str):
        """Unblock IP address"""
        try:
            subprocess.run([
                'iptables', '-D', CONFIG['iptables_chain'],
                '-s', ip, '-j', 'DROP'
            ], check=True)

            if ip in self.blocked_ips:
                del self.blocked_ips[ip]

            self.logger.info(f"Unblocked IP: {ip}")

        except Exception as e:
            self.logger.error(f"Failed to unblock IP {ip}: {e}")

    def handle_port_knock(self, packet):
        """Handle port knocking sequence"""
        if TCP in packet and packet[TCP].dport in CONFIG['port_knock_sequence']:
            src_ip = packet[IP].src
            port = packet[TCP].dport

            self.port_knock_attempts[src_ip].append({
                'port': port,
                'timestamp': datetime.now()
            })

            # Keep only recent attempts
            cutoff = datetime.now() - timedelta(seconds=30)
            self.port_knock_attempts[src_ip] = [
                attempt for attempt in self.port_knock_attempts[src_ip]
                if attempt['timestamp'] > cutoff
            ]

            # Check for correct sequence
            recent_attempts = self.port_knock_attempts[src_ip]
            if len(recent_attempts) >= len(CONFIG['port_knock_sequence']):
                ports = [attempt['port'] for attempt in recent_attempts[-len(CONFIG['port_knock_sequence']):]]
                if ports == CONFIG['port_knock_sequence']:
                    self.logger.info(f"Valid port knock sequence from {src_ip}")
                    # Add IP to temporary whitelist
                    self.whitelist_ip_temporarily(src_ip, 3600)  # 1 hour
                    self.port_knock_attempts[src_ip] = []  # Reset attempts

    def whitelist_ip_temporarily(self, ip: str, duration: int):
        """Temporarily whitelist IP address"""
        # Implementation would add IP to temporary whitelist
        self.logger.info(f"Temporarily whitelisted IP {ip} for {duration} seconds")
        # Schedule removal from whitelist
        threading.Timer(duration, self.remove_temporary_whitelist, args=[ip]).start()

    def remove_temporary_whitelist(self, ip: str):
        """Remove IP from temporary whitelist"""
        self.logger.info(f"Removed {ip} from temporary whitelist")

    def packet_handler(self, packet):
        """Main packet handler"""
        if IP not in packet:
            return

        src_ip = packet[IP].src
        dst_port = None
        protocol = "Unknown"
        flags = None

        # Extract connection details
        if TCP in packet:
            dst_port = packet[TCP].dport
            protocol = "TCP"
            flags = str(packet[TCP].flags)
        elif UDP in packet:
            dst_port = packet[UDP].dport
            protocol = "UDP"
        elif ICMP in packet:
            protocol = "ICMP"

        # Create connection record
        if dst_port:
            conn = ConnectionRecord(
                source_ip=src_ip,
                destination_port=dst_port,
                timestamp=datetime.now(),
                protocol=protocol,
                flags=flags
            )
            self.connection_records.append(conn)

        # Handle port knocking
        self.handle_port_knock(packet)

        # Periodically check for scans
        if len(self.connection_records) % 100 == 0:
            self.check_for_scans()

    def check_for_scans(self):
        """Check for scanning activity"""
        recent_connections = [
            conn for conn in self.connection_records
            if datetime.now() - conn.timestamp < timedelta(seconds=CONFIG['time_window'])
        ]

        scan_event = self.detect_port_scan(recent_connections)
        if scan_event:
            self.handle_scan_event(scan_event)

    def handle_scan_event(self, event: ScanEvent):
        """Handle detected scanning event"""
        self.logger.warning(f"Scan detected: {event.scan_type} from {event.source_ip} ({event.geo_location})")

        # Record scan event
        self.scan_events.append(event)
        self.scan_statistics[event.scan_type] += 1

        # Block IP based on scan type
        if "Critical" in event.scan_type:
            self.block_ip(event.source_ip, f"Critical port scanning: {event.scan_type}")
        elif len(event.ports_scanned) > 100:
            self.block_ip(event.source_ip, f"Comprehensive port scanning: {event.scan_type}")
        else:
            self.logger.warning(f"Monitoring IP {event.source_ip} for suspicious activity")

    def start_packet_capture(self):
        """Start packet capture using scapy"""
        self.logger.info("Starting packet capture...")
        sniff(
            filter="tcp or udp or icmp",
            prn=self.packet_handler,
            store=False
        )

    def start_system_monitoring(self):
        """Monitor system connections"""
        self.logger.info("Starting system connection monitoring...")

        while True:
            try:
                # Get current connections
                connections = psutil.net_connections()

                for conn in connections:
                    if conn.status == 'ESTABLISHED' and conn.raddr:
                        src_ip = conn.raddr.ip
                        dst_port = conn.raddr.port

                        # Create connection record
                        record = ConnectionRecord(
                            source_ip=src_ip,
                            destination_port=dst_port,
                            timestamp=datetime.now(),
                            protocol=conn.type.name if conn.type else "Unknown"
                        )
                        self.connection_records.append(record)

                time.sleep(5)  # Check every 5 seconds

            except Exception as e:
                self.logger.error(f"Error in system monitoring: {e}")
                time.sleep(10)

    def start_log_monitoring(self):
        """Monitor system logs for suspicious activity"""
        log_files = [
            '/var/log/auth.log',
            '/var/log/secure',
            '/var/log/messages'
        ]

        for log_file in log_files:
            if os.path.exists(log_file):
                threading.Thread(
                    target=self.monitor_log_file,
                    args=(log_file,),
                    daemon=True
                ).start()

    def monitor_log_file(self, log_file: str):
        """Monitor specific log file"""
        try:
            with open(log_file, 'r') as f:
                f.seek(0, 2)  # Go to end of file

                while True:
                    line = f.readline()
                    if line:
                        self.process_log_line(line.strip())
                    else:
                        time.sleep(1)

        except Exception as e:
            self.logger.error(f"Error monitoring log file {log_file}: {e}")

    def process_log_line(self, line: str):
        """Process individual log line for security events"""
        # SSH brute force detection
        if "sshd" in line and "Invalid user" in line:
            ip_match = re.search(r'from (d+.d+.d+.d+)', line)
            if ip_match:
                ip = ip_match.group(1)
                self.logger.warning(f"SSH invalid user attempt from {ip}")

        # Failed authentication attempts
        if "authentication failure" in line.lower():
            ip_match = re.search(r'(d+.d+.d+.d+)', line)
            if ip_match:
                ip = ip_match.group(1)
                # Track failed attempts and potentially block
                self.track_failed_authentication(ip)

    def track_failed_authentication(self, ip: str):
        """Track failed authentication attempts"""
        # Implementation would track failed attempts and block if threshold exceeded
        pass

    def start_monitoring(self):
        """Start all monitoring threads"""
        # Packet capture thread
        capture_thread = threading.Thread(
            target=self.start_packet_capture,
            daemon=True
        )
        capture_thread.start()

        # System monitoring thread
        system_thread = threading.Thread(
            target=self.start_system_monitoring,
            daemon=True
        )
        system_thread.start()

        # Log monitoring thread
        log_thread = threading.Thread(
            target=self.start_log_monitoring,
            daemon=True
        )
        log_thread.start()

    def get_statistics(self) -> Dict:
        """Get current security statistics"""
        return {
            'blocked_ips': len(self.blocked_ips),
            'scan_events': len(self.scan_events),
            'scan_types': dict(self.scan_statistics),
            'monitored_connections': len(self.connection_records),
            'port_knock_attempts': len(self.port_knock_attempts),
            'uptime': time.time() - self.start_time if hasattr(self, 'start_time') else 0
        }

    def export_report(self, filename: str):
        """Export security report to JSON file"""
        report = {
            'timestamp': datetime.now().isoformat(),
            'statistics': self.get_statistics(),
            'blocked_ips': {ip: asdict(data) for ip, data in self.blocked_ips.items()},
            'recent_scans': [asdict(event) for event in self.scan_events[-10:]]
        }

        with open(filename, 'w') as f:
            json.dump(report, f, indent=2, default=str)

        self.logger.info(f"Security report exported to {filename}")

def main():
    """Main function"""
    print("Network Scanning Detection and Protection System")
    print("=" * 50)

    # Check if running as root
    if os.geteuid() != 0:
        print("This script must be run as root for iptables functionality")
        return

    try:
        # Initialize detector
        detector = NetworkScanDetector()
        detector.start_time = time.time()

        print("Network scan detector started successfully!")
        print(f"Log file: {CONFIG['log_file']}")
        print(f"Monitoring interface: All interfaces")
        print(f"Critical ports: {CONFIG['critical_ports']}")
        print(f"Whitelisted IPs: {CONFIG['whitelist']}")
        print("\nPress Ctrl+C to stop monitoring...")

        # Keep main thread alive
        try:
            while True:
                time.sleep(60)
                # Print statistics every minute
                stats = detector.get_statistics()
                print(f"\rActive scans: {stats['scan_events']} | Blocked IPs: {stats['blocked_ips']} | Connections: {stats['monitored_connections']}", end='', flush=True)

        except KeyboardInterrupt:
            print("\n\nShutting down...")

            # Generate final report
            detector.export_report('/tmp/network_security_report.json')

            # Cleanup iptables
            try:
                subprocess.run(['iptables', '-F', CONFIG['iptables_chain']], check=False)
                subprocess.run(['iptables', '-D', 'INPUT', '-j', CONFIG['iptables_chain']], check=False)
                subprocess.run(['iptables', '-X', CONFIG['iptables_chain']], check=False)
            except:
                pass

            print("Cleanup completed. Security report saved to /tmp/network_security_report.json")

    except Exception as e:
        print(f"Error: {e}")
        import traceback
        traceback.print_exc()

if __name__ == "__main__":
    import os
    main()

工具

经常与该案例搭配使用的工具

相关内容

相关案例集合

相关内容

相关专题

专题

环境变量与配置格式治理工作流

在不暴露密钥的前提下解析、校验、转换、合并并比较配置,记录事实来源。

专题

容器发布前的 Dockerfile 与环境配置审查

检查 Dockerfile 规则、镜像引用格式与环境变量重复键,解释预发布和生产配置差异,形成可核对的容器发布记录。

专题

自托管抽奖组件配置复核、嵌入测试与上线交付

复核转盘、刮刮卡或盲盒的配置与商家接口样例,检查可读性和移动端布局,交付版本明确的组件文件及真实浏览器验收记录。

专题

校验位与校验和验证

规范化标识符,选择规范指定的校验路径,并在接受前检查格式。

首页
工具3212
案例593
可视化471
文件查看器103
专题239
标签333
图像、音频与视频657

图像、音频、视频处理、转换与优化工具

数学、日期与金融647

计算器、数值计算、日期逻辑、统计与金融工具

设计与颜色298

颜色、版式、图形、视觉样式与设计辅助工具

文本与写作209

写作、清洗、格式化、提取与文本分析工具

开发与 Web193

开发者工具、网络处理、Web 调试与自动化辅助工具

转换与编码175

格式、文件、压缩包、单位与编码转换工具

潜客测验发布与联系人交接
讣告、悼词与纪念卡的家属复核及交付
本地习惯记录的备份、恢复演练与分享前检查
长文改编 X 串文与 LinkedIn 帖子的事实复核与交付
Markdown 互动课件审校、离线演示与交付

© 2026 Elysia Tools. 保留所有权利。

文档价格关于我们服务条款隐私政策Cookie 政策联系我们

Development

SSL检查器

检查SSL证书信息、有效性和安全配置

Format Conversion

GraphML / GEXF / 边列表网络转换器

在 GraphML、GEXF、DOT、邻接矩阵和边列表 CSV 间转换,并预览网络指标

Security

JWT 解码与安全审计器

解码 JWT Header/Payload,校验 HS256 或 RS256 签名,并检查算法、过期时间与敏感 claim 风险

Data Visualization

网络图生成器

交互式网络关系图,用于可视化社交网络、拓扑结构和节点连接

Network

网络包解析器

解析 pcap 和基础 pcapng 抓包文件,展示协议、会话和时间线统计,并支持导出过滤后的结果。

Security

安全响应头检查器

审计 HTTP 响应头的安全合规性——解析你粘贴的原始头(无网络),按 OWASP 安全头集做值级检查:HSTS max-age、CSP unsafe-inline/eval、X-Content-Type-Options、Referrer-Policy、Permissions-Policy、COOP/COEP/CORP 等。输出字母评级(A+ 到 F)及逐项 Finding 与可复制的修复建议。

Science & Education

电子排布计算器

按元素符号或原子序数查询电子排布、壳层分布、价电子和轨道图

Math & Numbers

PERT 网络分析器(期望工期/方差/完工概率)

对 2–20 个活动做 PERT 三点估计分析(每行:名称、乐观 a、最可能 m、悲观 b、紧前活动):te = (a+4m+b)/6,σ² = ((b−a)/6)²;在 te 上运行 CPM 得关键路径、期望项目工期 TE 与项目方差(关键路径上 σ² 之和);给出目标工期 T 时按正态近似计算 Z = (T−TE)/σ 与完工概率 Φ(Z)。a≤m≤b 违规、循环依赖按业务拒绝;σ≈0 的确定性网络按确定性处理。经典例:A(2,4,6)、B(3,5,7)、C(2,3,10)、D(4,6,8, B C) → TE = 15,σ² = 1.3333,T = 16 时概率 ≈ 80.7%。

安全

JWT 示例

从基础令牌结构到高级安全实现的全面JWT示例

安全

包含敏感数据的日志文件

包含各种类型个人身份信息(PII)的日志文件样本,用于测试PII检测和日志脱敏工具

安全

SQL注入示例

用于安全测试、漏洞评估和防御编码实践的SQL注入载荷教育集合

安全

XSS跨站脚本载荷示例

跨站脚本(XSS)载荷的教育集合,用于安全测试和验证

区块链

Hardhat 开发框架示例

Hardhat 以太坊开发环境示例,包括智能合约、测试、部署、脚本、插件和开发工作流

测试

Jest 测试框架

全面的Jest测试示例,包括单元测试、集成测试、模拟、异步测试和JavaScript/TypeScript应用的高级模式