Operations 48 min read

How to Tackle Excess Connections, DDoS/DoS, CORS and XSS Attacks – A Complete Practical Guide

This article walks through a systematic, production‑grade approach to diagnosing and mitigating connection‑overload, DoS/DDoS, XSS and cross‑origin attacks, covering log analysis, Linux kernel tuning, Nginx rate‑limiting, CDN/DDoS‑protection layers, WAF rules, safe rendering practices, and a hardened CORS configuration template.

Tech Freedom Circle
Tech Freedom Circle
Tech Freedom Circle
How to Tackle Excess Connections, DDoS/DoS, CORS and XSS Attacks – A Complete Practical Guide

Network Connection Surge Detection and Mitigation

When a server suddenly shows >3000 connections per minute, start with the access log as the first line of defense. The classic Linux pipeline below lists the top 10 IPs by request count (normal users < 50/min, >200/min is suspicious):

tail -1000 /var/log/nginx/access.log | awk '{print $1}' | sort | uniq -c | sort -nr | head -10

Check half‑open TCP connections to spot a SYN flood: netstat -an | grep :80 | grep SYN_RECV | wc -l If the SYN_RECV count exceeds 100, a SYN‑Flood is likely.

Kernel Parameter Hardening

Edit /etc/sysctl.conf and apply with sudo sysctl -p. The following parameters are proven for small‑to‑medium sites (2 CPU / 4 GB RAM): net.ipv4.tcp_syncookies = 1 – enables SYN cookies to avoid queue exhaustion. net.ipv4.tcp_max_syn_backlog = 4096 – enlarges the half‑connection backlog (default is often 128). net.ipv4.tcp_synack_retries = 1 – reduces the time a half‑open connection occupies the queue. net.ipv4.tcp_tw_reuse = 1 and net.ipv4.tcp_fin_timeout = 30 – recycle TIME_WAIT sockets faster. net.core.somaxconn = 1024 – expands the full‑connection queue; must match listen 80 backlog=1024 in Nginx.

Verify the changes:

# Verify backlog size
sysctl net.ipv4.tcp_max_syn_backlog
# Check TIME_WAIT reduction
ss -s | grep timewait

Nginx Rate‑Limiting

Define shared memory zones in the http block:

limit_req_zone $binary_remote_addr zone=req_limit:10m rate=10r/s;
limit_conn_zone $binary_remote_addr zone=conn_limit:10m;
limit_conn_zone $server_name zone=domain_conn_limit:10m;

Apply limits per server:

limit_conn conn_limit 15;               # max 15 connections per IP
limit_conn domain_conn_limit 200;      # max 200 connections per domain
limit_req zone=req_limit burst=20 nodelay;  # 10 req/s, burst up to 20

Return 429 for limit violations so the client can retry.

DoS / DDoS Overview and Countermeasures

DoS is a single‑source flood; DDoS is a distributed flood. Three families of attacks are relevant:

Traffic‑layer DDoS (UDP/ICMP flood) – exhausts bandwidth.

Connection‑layer DDoS (SYN/ACK flood, Slowloris) – exhausts TCP connection tables.

Application‑layer DDoS (CC / Challenge Collapsar Attack) – sends legitimate‑looking HTTP requests to drain CPU, DB connections, or application threads.

Mitigation Stack for Small‑to‑Medium Sites

Enable the cloud provider’s free basic DDoS protection (usually 2‑10 Gbps).

Close all unused ports with iptables or ufw.

Apply the kernel hardening parameters shown above.

Configure Nginx limit_conn and limit_req as described.

Set short timeouts to stop Slowloris:

client_header_timeout 10s;
client_body_timeout 10s;
send_timeout 10s;

Deploy a CDN (Alibaba Cloud, Cloudflare) to hide the origin IP and cache static assets.

For higher risk, purchase a high‑defense IP or anti‑DDoS appliance and restrict source IPs to the protection service.

Enable a lightweight WAF (Alibaba Cloud WAF, Tencent Cloud WAF) to block known malicious signatures.

Implement business‑level degradation (e.g., disable comments, limit login attempts) using circuit‑breaker libraries such as Spring Cloud Sentinel.

Testing tools (run only against your own infrastructure): hping3 -S -p 80 -i u100 target_ip – SYN flood simulation. slowloris Python script – Slowloris attack. ab -n 1000 -c 20 http://your-site.com/ – load test to verify rate limiting (expect many 429 responses).

XSS (Cross‑Site Scripting) Protection

XSS attacks execute malicious scripts in the victim’s browser. Three attack families exist:

Stored XSS – payload is saved in the database (e.g., comment field) and served to every visitor.

Reflected XSS – payload is reflected via URL parameters or headers back to the user.

DOM‑based XSS – client‑side JavaScript inserts untrusted data into the DOM without proper sanitisation.

Four‑Layer Defense

Input Validation – whitelist allowed characters. Example utility:

function validateInput(input, pattern) {
  const whitelist = {
    username: /^[a-zA-Z0-9_-]{3,20}$/,
    email: /^[^\s@]+@[^\s@]+\.[^\s@]+$/,
    content: /^[\w\s\u4e00-\u9fa5,!?;:'"-]{1,1000}$/
  };
  return whitelist[pattern].test(input);
}

Output Encoding – escape data according to the rendering context (HTML, attribute, JavaScript, URL). For HTML body escape < > & " '; for URLs use encodeURIComponent; for JavaScript strings use backslash escaping.

Safe Rendering – avoid dangerous DOM APIs. Prefer textContent over innerHTML, never use eval or document.write. In frameworks, rely on automatic escaping (Vue {{ }}, React {}) and only use v-html or dangerouslySetInnerHTML after sanitising with a library such as DOMPurify:

import DOMPurify from 'dompurify';
const clean = DOMPurify.sanitize(dirtyHTML, {
  ALLOWED_TAGS: ['p','br','strong','em','ul','ol','li','a'],
  ALLOWED_ATTR: ['href','class'],
  ADD_URI_SAFE_ATTR: ['target']
});

Framework‑Level Safeguards – Vue automatically HTML‑escapes interpolations; React does the same. If you must render raw HTML, combine the framework’s feature with DOMPurify as shown above.

The overall formula is:

Input Validation × Output Encoding × Safe Rendering = XSS‑Free

CORS (Cross‑Origin Resource Sharing) Secure Configuration

Browsers enforce the Same‑Origin Policy (protocol, host, port must match). CORS provides a controlled way to relax this rule.

Key Response Headers

Access-Control-Allow-Origin

– must specify an exact origin; never use * when credentials are involved. Access-Control-Allow-Methods – list only the HTTP methods you need (e.g., GET, POST, OPTIONS). Access-Control-Allow-Headers – list only required request headers (e.g., Content-Type, Authorization, X-Requested-With). Access-Control-Allow-Credentials – set to true only when you need to send cookies; it must be paired with a specific Access-Control-Allow-Origin. Access-Control-Max-Age – cache the pre‑flight response (e.g., 86400 seconds) to reduce OPTIONS traffic.

Secure Nginx Example

The snippet below implements a strict whitelist, handles pre‑flight requests, and adds the necessary CORS headers only for trusted origins:

# Inside the server{} block handling API traffic
# 1. Detect a trusted Origin and store it in $allowed_origin
if ($http_origin ~* ^(https?://(www|m)example\.com(:[0-9]+)?$)) {
    set $allowed_origin $http_origin;
}
# 2. Pre‑flight (OPTIONS) handling
if ($request_method = OPTIONS) {
    add_header 'Access-Control-Allow-Origin' "$http_origin";
    add_header 'Access-Control-Allow-Methods' 'GET, POST, PUT, DELETE, OPTIONS';
    add_header 'Access-Control-Allow-Headers' 'Content-Type, Authorization, X-Requested-With';
    add_header 'Access-Control-Max-Age' '86400';
    add_header 'Content-Length' '0';
    add_header 'Content-Type' 'text/plain';
    return 204;
}
# 3. Normal requests – add CORS headers only for whitelisted origins
if ($allowed_origin != "") {
    add_header 'Access-Control-Allow-Origin' "$allowed_origin" always;
    add_header 'Access-Control-Allow-Credentials' 'true' always;
    add_header 'Access-Control-Expose-Headers' 'X-Token-Expire, X-Data-Total' always;
}
# Proxy to backend
proxy_pass http://backend:3000;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;

Important notes:

Never use Access-Control-Allow-Origin: * together with Access-Control-Allow-Credentials: true – browsers will reject the response.

Keep the whitelist as narrow as possible; include CDN domains if you serve assets through a CDN.

Set cookie attributes HttpOnly, Secure, and SameSite=Strict|Lax to mitigate CSRF even when CORS is correctly configured.

Practical Checklist

Inspect access logs for IP concentration, unusual paths, and abnormal time patterns.

Run netstat -an | grep SYN_RECV to detect SYN‑Flood spikes.

Apply kernel hardening parameters and reload with sysctl -p.

Configure Nginx limit_conn and limit_req per IP and per domain.

Set short client timeouts ( client_header_timeout 10s;, client_body_timeout 10s;, send_timeout 10s;) to stop Slowloris.

Enable cloud provider basic DDoS protection and hide the origin IP behind a CDN.

For higher‑risk services, purchase a high‑defense IP or anti‑DDoS appliance and restrict inbound traffic to the protection service.

Deploy a lightweight WAF and fine‑tune rules for CC attacks.

Implement business‑level degradation (disable non‑essential features) during an attack.

Sanitise all user‑generated content, enforce whitelist validation, and use context‑aware output encoding.

Never use innerHTML, eval, or document.write with untrusted data.

Configure strict CORS (specific origin, limited methods/headers, credentials only when needed).

Test the whole stack on a staging environment with tools such as hping3, slowloris, and ab.

backendCORSNginxnetwork securityDDoS mitigationXSS protectionLinux kernel tuning
Tech Freedom Circle
Written by

Tech Freedom Circle

Crazy Maker Circle (Tech Freedom Architecture Circle): a community of tech enthusiasts, experts, and high‑performance fans. Many top‑level masters, architects, and hobbyists have achieved tech freedom; another wave of go‑getters are hustling hard toward tech freedom.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.