When a security breach hits, the clock starts ticking. The first hour can determine whether you suffer a contained incident or a full-blown crisis. This guide shows you how to detect and contain three of the most common threats—SQL injections, DDoS attacks, and unauthorized access attempts—within 60 minutes, with practical steps, tools, and scripts you can put to work immediately.
The First Hour Mindset: Contain, Don’t Panic
In those first critical minutes, your goals are simple:
- Identify the breach type and scope.
- Stop the bleeding without destroying evidence.
- Protect customer data and critical systems.
- Communicate clearly and assign ownership.
Everything else—root cause analysis, long-term remediation, and disclosures—comes after containment.
Quick Indicators: Know What You’re Dealing With
Understanding early signals helps you triage efficiently.
SQL Injection (SQLi) — Indicators
- Spikes in 500/502 errors on endpoints that make database calls.
- Logs showing unusual characters in input fields or URLs (quotes, comment markers, UNION/SELECT, sleep/delay).
- Database CPU spikes, long-running queries, or locks.
- WAF alerts for injection patterns.
DDoS (Layer 3/4 and Layer 7) — Indicators
- Sudden traffic surges, high connection counts, or bandwidth saturation.
- Application-level symptoms: high request rate to specific endpoints, timeouts, 503 responses.
- Load balancer logs showing a handful of IPs generating disproportionate traffic.
- CDN/Firewall dashboards flagging anomalies.
Unauthorized Access — Indicators
- Multiple failed logins followed by a successful one from a new location.
- “Impossible travel” or login from unknown devices.
- Privilege escalations, creation of new admin accounts, or changes to MFA.
- Unusual API usage or data exfiltration patterns.
The First 60 Minutes: A Playbook
Use this time-boxed checklist to organize your response.
Minutes 0–5: Confirm and Triage
- Declare the incident; assign an incident commander (IC) and scribe.
- Spin up a war room (e.g., incident channel) and ticket.
- Identify the suspected attack category: SQLi, DDoS, or unauthorized access.
- Start preserving evidence: enable or snapshot logs and relevant telemetry.
Minutes 5–15: Stabilize and Isolate
- For SQLi: Enable WAF blocking mode if safe; geofence and rate-limit suspicious sources.
- For DDoS: Turn on CDN under-attack mode, rate limiting, and challenge pages.
- For unauthorized access: Disable suspicious accounts, revoke tokens, isolate compromised endpoints.
- Notify stakeholders (security, ops, support) and pause risky deployments.
Minutes 15–30: Contain and Verify
- Update firewall/WAF rules to block offending IPs or request patterns.
- Rotate exposed credentials and disable compromised API keys.
- Enforce MFA where it’s missing; invalidate user sessions if accounts are impacted.
- Check blast radius: which services, regions, and datasets are affected?
Minutes 30–60: Hardening and Monitoring
- Patch emergency configuration (e.g., enforce parameterized queries, remove vulnerable endpoints temporarily).
- Scale or reroute traffic (CDN, load balancer) for DDoS resilience.
- Baseline post-containment metrics; watch for attack pivots.
- Prepare an internal briefing and a customer comms draft (do not send publicly until confirmed).
SQL Injection: Detect and Contain in Under an Hour
SQLi aims to manipulate database queries via untrusted input. Your immediate goal is to block malicious inputs, limit database damage, and secure credentials.
Step 1: Detect Fast
Check web and WAF logs for unusual patterns:
- Unexpected single quotes, comment markers (e.g., “--”, “/*”), or stacked queries.
- Keywords like SELECT, UNION, INFORMATION_SCHEMA in user input.
- Database errors surfaced in responses.
Examples: Queries for SIEM/Splunk/Elastic to flag potential SQLi.
Splunk:
index=web_logs (status>=500 OR uri_query="*'*" OR uri_query="*--*" OR uri_query="*/*" OR uri_query="*union*")
| stats count by src_ip, uri, status
| sort - count
Elastic (Lucene/KQL):
(status >= 500 OR url.query:("*'*" OR "*--*" OR "*/*" OR "*union*"))
| stats count by client.ip, url.path, http.response.status_code
ModSecurity/CRS-aligned WAF rule detection:
SecRuleEngine On
SecDefaultAction "phase:2,deny,log"
SecRule ARGS|ARGS_NAMES|REQUEST_URI "@detectSQLi" "id:1001,phase:2,deny,log,msg:'SQLi pattern detected'"
Database-side indicators:
- MySQL: look at slow query log and general log for unexpected queries.
- Postgres: check pg_stat_activity for long-running or suspicious queries.
Postgres quick check:
SELECT pid, usename, application_name, client_addr, query, state, now()-query_start AS runtime
FROM pg_stat_activity
WHERE state <> 'idle' AND (now()-query_start) > interval '5 seconds';
Step 2: Immediate Containment
- Turn on blocking in your WAF with SQLi rules. If in detect-only, switch to block mode temporarily.
- Rate-limit or temporarily disable endpoints most targeted (e.g., /search, /login, /product).
- Block offending IP ranges if concentrated; prefer challenge/JS validation for distributed patterns.
Nginx rate limiting (Layer 7):
http {
limit_req_zone $binary_remote_addr zone=req_limit:10m rate=10r/s;
server {
location /search {
limit_req zone=req_limit burst=20 nodelay;
proxy_pass http://app_backend;
}
}
}
Temporary IP block (Linux; use carefully and document):
sudo iptables -I INPUT -s 203.0.113.0/24 -j DROP
# or nftables
sudo nft add rule inet filter input ip saddr 203.0.113.0/24 drop
- Put the application in degraded or read-only mode if feasible to prevent destructive writes.
- Rotate DB credentials used by the affected service. Ensure least privilege on new credentials.
MySQL: immediately revoke risky grants from app user:
REVOKE DROP, ALTER, CREATE ON *.* FROM 'app_user'@'%';
FLUSH PRIVILEGES;
Step 3: Validate and Reduce Blast Radius
- Confirm that no table schema changes or mass data exports occurred.
- Check for unexpected admin accounts or database users created during the window.
- Snapshot critical tables for forensics and recovery points.
MySQL schema change check (last 24h via information_schema, if available):
SELECT event_time, user_host, argument
FROM mysql.general_log
WHERE command_type='Query' AND argument REGEXP 'CREATE|ALTER|DROP'
AND event_time > NOW() - INTERVAL 1 DAY;
Step 4: Short-Term Hardening (within the hour)
- Enforce parameterized queries across hot paths (review the top-traffic endpoints).
- Escape and validate user inputs server-side; disable debug error messages to end users.
- Add WAF virtual patches targeting affected endpoints:
SecRule REQUEST_URI "@beginsWith /search" "id:1002,phase:2,deny,log,chain,msg:'Virtual patch for SQLi on /search'"
SecRule ARGS_NAMES|ARGS "@rx (?i)(select|union|sleep|benchmark|information_schema)"
Practical Example: Minimal “Virtual Patch” Loop
- Identify the top 5 abused endpoints.
- Add denylist patterns for numeric-only fields that receive non-numeric input.
- Introduce server-side sanity checks for length and allowed character sets.
Example for an integer-only parameter:
# Nginx: reject non-digits on id parameter
if ($arg_id !~ "^[0-9]+$") { return 403; }
DDoS: Detect and Contain Without Taking Yourself Offline
DDoS comes in flavors:
- Network/transport floods (SYN, UDP, amplification).
- Application layer (HTTP floods, login hammering, search endpoint overload).
Your aim: absorb or deflect traffic, maintain availability for legitimate users, and avoid cascading failures.
Step 1: Identify the Attack Type
- Check CDN/load balancer dashboards for traffic sources, protocols, and throughput.
- Verify whether the origin is saturated or just app instances are overloaded.
- Look for patterns: single endpoint targeted, login attempts, massive POST traffic.
Quick system snapshot:
# Connection counts by state
ss -s
# Top talking IPs
sudo netstat -ntu | awk '{print $5}' | cut -d: -f1 | sort | uniq -c | sort -nr | head
# Nginx status (if enabled)
curl -s http://127.0.0.1/nginx_status
Step 2: Contain via Edge Controls
- Turn on “Under Attack”/challenge mode on your CDN (e.g., Cloudflare, Akamai).
- Deploy rate limiting on hot endpoints:
- Lower thresholds on POST/expensive routes (/login, /search, /checkout).
- Apply stricter limits for anonymous traffic.
- Enable bot management and JS challenges for high-risk paths.
Cloud provider specifics (quick toggles):
- AWS: Enable AWS Shield Advanced if available; tighten AWS WAF rules; use ALB with target group health checks and request-based scaling. Add rate-based rules:
{
"Name": "RateLimitLogin",
"Priority": 1,
"Statement": {
"RateBasedStatement": {
"Limit": 2000,
"AggregateKeyType": "IP",
"ScopeDownStatement": {
"ByteMatchStatement": {
"FieldToMatch": { "UriPath": {} },
"PositionalConstraint": "STARTS_WITH",
"SearchString": "/login",
"TextTransformations": [{ "Priority": 0, "Type": "LOWERCASE" }]
}
}
}
},
"Action": { "Block": {} },
"VisibilityConfig": { "SampledRequestsEnabled": true, "CloudWatchMetricsEnabled": true, "MetricName": "RateLimitLogin" }
}
- GCP: Use Cloud Armor preconfigured WAF rules and rate limits; route via Cloud CDN.
- Azure: Enable Azure DDoS Protection; apply WAF policies on Application Gateway/Front Door.
Step 3: Origin Protection
- Scale horizontally if needed; increase instance counts via auto-scaling.
- Drop malformed or clearly abusive traffic at the network edge:
# Drop SYNs exceeding rate (example; tune carefully)
sudo iptables -A INPUT -p tcp --syn -m limit --limit 50/second --limit-burst 100 -j ACCEPT
sudo iptables -A INPUT -p tcp --syn -j DROP
- If the attack is saturating bandwidth, coordinate with ISP or cloud provider for upstream filtering/scrubbing.
Step 4: Validate and Monitor
- Verify key SLOs: error rates, latency, success responses.
- Watch for attacker pivot to new endpoints; preemptively protect them.
- Ensure rate limits aren’t blocking legitimate high-volume partners; whitelist by authenticated identity if possible.
Practical Example: Layer 7 Focused Defense
- Implement a 5 requests/second rate limit on /login and /search for unauthenticated users.
- Add CAPTCHA/JS challenge for repeated requests to POST /login.
- Cache GET responses aggressively on CDN for static and semi-static pages.
Unauthorized Access: Detect, Expel, and Lock Down
This scenario involves a valid but compromised credential or an attacker bypassing authentication/authorization. Your goal is to kick them out quickly and shut the doors they used.
Step 1: Detect the Intrusion
- SIEM alerts for:
- Logins from anomalous geo-locations or unfamiliar devices.
- Privilege escalation events (role changes, new admin creation).
- Sudden spikes in data export/download.
- MFA deactivation or backup method add events.
Splunk sample search:
index=auth_logs (action="login_success" OR action="privilege_change" OR action="mfa_change")
| stats earliest(_time) as first_seen, latest(_time) as last_seen, values(action) as actions, count by user, src_ip, device
| where count > 10 OR like(actions, "%privilege_change%") OR like(actions, "%mfa_change%")
Cloud logs to inspect:
- AWS CloudTrail: CreateUser, AttachUserPolicy, CreateAccessKey, UpdateLoginProfile, PutRolePolicy, AssumeRole unusual patterns.
- Azure AD: AddMemberToRole, UpdatePolicy.
- Google Workspace: Admin privilege changes.
Step 2: Expel the Intruder
- Disable or lock the compromised account immediately.
- Invalidate all active sessions and revoke refresh tokens.
- Rotate associated API keys and secrets.
Examples:
- Linux lock:
sudo usermod -L suspicious_user
- AWS IAM (disable access key):
aws iam update-access-key --access-key-id AKIA... --status Inactive --user-name compromised_user
-
Force-password reset and enforce MFA enrollment:
- For IdP (Okta/Azure AD/Google Workspace), mark user to reset password and require MFA.
-
Isolate compromised endpoints using your EDR (e.g., put host in containment network).
Step 3: Contain Scope and Prevent Lateral Movement
- Temporarily restrict high-privilege roles; adopt break-glass accounts with separate MFA.
- Harden network segmentation: deny admin interfaces from public networks; allowlist office/VPN IPs only.
- Audit recent role changes, new users, OAuth app grants.
CloudTrail quick query (Athena):
SELECT eventtime, useridentity.principalid, eventname, sourceipaddress
FROM cloudtrail_logs
WHERE eventtime > current_timestamp - interval '1' hour
AND eventname IN ('CreateUser','CreateAccessKey','AttachUserPolicy','PutUserPolicy','AddUserToGroup','PassRole','AssumeRole');
Step 4: Validate Data Access
- Check for mass exports (S3 GET/List, database dumps, report downloads).
- Throttle or temporarily disable export/report features.
S3 server access logs (Athena sample):
SELECT requester, count(*) AS gets, sum(bytes_sent) as bytes
FROM s3_access_logs
WHERE requestdatetime > current_timestamp - interval '1' hour
AND operation = 'REST.GET.OBJECT'
GROUP BY requester
ORDER BY bytes DESC
LIMIT 20;
Preserve Evidence Without Blocking Yourself
Containment must not destroy forensic trails:
- Snapshot relevant instances or volumes before wiping.
- Export and archive logs to write-once storage (e.g., S3 with object lock).
- Record command history used during response.
- Maintain a simple chain-of-custody log:
- Who accessed what, when, and why.
- Hashes of downloaded artifacts.
Communication That Helps, Not Hurts
- Internal: Share current facts, not speculation; document decisions and owners.
- External: Prepare a holding statement; don’t publish until you confirm scope.
- Legal/compliance: Notify counsel early; check regulatory timelines for breach notifications.
Template for incident channel topic:
- Incident: [Short description]
- IC: [Name]
- Scribe: [Name]
- Suspected Type: [SQLi/DDoS/Unauthorized]
- Impacted Systems: [List]
- Actions Taken: [Bullets]
- Next Review: [Time]
Practical Runbooks You Can Reuse
10-Minute SQLi Containment Runbook
- Switch WAF from monitor to block for SQLi rules.
- Rate-limit and geo-challenge the top attacked endpoints.
- Rotate app DB credentials and restrict privileges.
- Disable or hide vulnerable forms temporarily.
- Baseline errors and DB CPU; monitor for changes.
10-Minute DDoS Runbook
- Enable CDN under-attack mode and rate limiting.
- Cache aggressively on CDN; serve stale on errors.
- Scale out app instances and verify health checks.
- Drop obviously abusive IP ranges; coordinate upstream if volumetric.
- Monitor success rate and latency.
10-Minute Unauthorized Access Runbook
- Disable suspicious accounts and keys; force session invalidation.
- Require MFA and password reset.
- Isolate impacted endpoints via EDR.
- Review last hour of admin actions and reverse malicious changes.
- Monitor for reattempts and password sprays.
Common Pitfalls to Avoid
- Turning off all traffic indiscriminately; aim for targeted mitigation to keep legitimate users online.
- Deleting logs during cleanup; always snapshot first.
- Over-blocking and breaking integrations; use identity-aware allowlists for partners.
- Assuming a single attack type; watch for chained attacks (e.g., DDoS as cover for intrusion).
Actionable Hardening After the First Hour
Once contained, move to eradication and long-term fixes.
For SQLi
- Adopt prepared statements/ORM parameterization across all data access layers.
- Add input validation libraries and centralized sanitization.
- Implement database row-level permissions and per-service credentials.
- Expand WAF coverage with positive security models (allow only expected patterns).
For DDoS
- Establish baselines and automatic anomaly detection on edge and origin.
- Implement tiered rate limiting by user role and authentication status.
- Use anycast CDNs and ensure DNS is resilient (DNS provider with DDoS protection).
- Build a traffic shed plan: degrade non-essential features under load.
For Unauthorized Access
- Enforce MFA everywhere, especially for admins and programmatic access.
- Rotate all long-lived credentials; prefer short-lived, scoped tokens (OIDC/SAML, STS).
- Implement conditional access: device trust, geo/ip allowlists, risk-based policies.
- Log and alert on privilege changes, API key creation, and MFA disable events.
Metrics That Signal Containment
Track these to know you’re turning the corner:
- Error rate stabilized within normal variance.
- Request rate vs. successful responses recovering.
- Database CPU/IO back to baseline; no new suspicious queries.
- No new admin actions or anomalous logins after lockouts.
- WAF/firewall drops taper off or plateau.
Simple Decision Tree for the First Hour
- See massive traffic spike?
- If bandwidth/connection-level: DDoS (L3/4) → enable upstream protection, scrubbing, rate limits.
- If endpoint-specific with normal bandwidth: DDoS (L7) → CDN challenges, rate limits, cache.
- See 500 errors on DB-backed endpoints with odd parameters?
- Likely SQLi → enable WAF SQLi blocking, restrict DB privileges, rotate creds.
- See unusual logins or admin activity?
- Unauthorized access → disable accounts/keys, invalidate sessions, enforce MFA, isolate hosts.
Quick Tools Checklist
- WAF/CDN: Turn on block mode, rate limits, CAPTCHA/JS challenge.
- SIEM: Prebuilt dashboards for login anomalies, error bursts, and WAF hits.
- EDR: One-click host isolation for compromised endpoints.
- Cloud: Shield/Armor/DDoS Protection; IAM key/role audit; activity logs.
- Networking: Security groups, iptables/nftables, upstream filtering.
Example: One-Hour War Room Agenda
- 0–5 min: Confirm attack type; assign roles; enable log preservation.
- 5–15 min: Apply edge controls (WAF/CDN); disable compromised identities.
- 15–30 min: Rotate critical secrets; isolate systems; validate KPIs.
- 30–45 min: Tighten rules; monitor for pivots; document actions.
- 45–60 min: Stabilize; draft internal summary; plan next steps (eradication, RCA).
Quick Wins You Can Implement Today
- Pre-create WAF policies for SQLi, path-based rate limits, and login throttling.
- Set up alert thresholds: 500 errors, login anomalies, and data egress spikes.
- Enforce MFA for all privileged accounts; ban long-lived access keys.
- Configure CDN under-attack profiles and verify you can toggle them in seconds.
- Practice a 30-minute incident drill with your team.
Final Thoughts
Speed and clarity win the first hour. Focus on:
- Precise detection signals for SQLi, DDoS, and unauthorized access.
- Immediate, targeted containment actions at the edge and identity layers.
- Preserving evidence and communicating clearly.
Make these steps muscle memory by preparing runbooks, automations, and drills. When the moment comes, you’ll move fast, contain effectively, and protect your users and data.