⚡ ~/naveed Tech Blog
⚡ Portfolio Home 👤 About Naveed Bio & Credentials ⚖️ Editorial Policy Standards & Trust 📫 Contact Naveed Get In Touch ✍️ Engineering Blog Deep Dives 🎯 Interview Hub 1,000+ Scenarios ☸️ Kubernetes Mastery Hub 24 Modules 🎮 DevOps Arcade & Quizzes Subnet Blitz ⚡ 🗺️ DevOps Roadmaps PDFs & Guides 🤖 Morpheus Analysis AI Quant ↗ 🛠️ Developer Tools Utilities 🧪 Labs & Experiments 📄 Interactive CV & Certs 🔗 All Links & Socials ⚡ Join The Dispatch (Weekly SRE Newsletter) →

How Next.js RCE Hijacked Our AWS Container: The 3 AM Incident Postmortem

How Next.js RCE Hijacked Our AWS Container: Forensic incident postmortem and DevSecOps architecture diagram

When AWS Trust & Safety flagged our account for outbound Telnet scanning, we thought it was a mistake—our app was running on a serverless container PaaS. Here is the forensic investigation of how an unauthenticated Next.js RCE turned our managed container into an internet scanner, and why managed cloud won't save vulnerable code.

The DevSecOps Executive Summary

The Incident: Discovering how Next.js RCE hijacked our AWS container began when a production container running on a managed cloud PaaS (AWS App Runner) was weaponized into a botnet scanner probing external WordPress sites and Telnet ports across the globe.
The Root Cause: An unauthenticated Remote Code Execution (RCE) in an unpatched modern web framework (Next.js 15.1.7 React Server Components serialization).
The Painful Lesson: Network-level egress filtering stopped the outbound scan, but inadvertently took our PostgreSQL database offline while leaving the inbound execution backdoor wide open. In modern cloud architecture, managed infrastructure does not relieve you of application-layer security.

1. The 3:00 AM Alert: Investigating How Next.js RCE Hijacked Our AWS Container

Investigating how Next.js RCE hijacked our AWS container began with an emergency 3:00 AM notification from AWS Trust and Safety reporting port 23 Telnet abuse scans. Even on managed serverless container platforms like AWS App Runner, unpatched application-layer vulnerabilities grant unauthenticated remote access, turning production workloads into distributed port-scanning nodes without triggering infrastructure-level alarms.

At 3:00 AM, the automated email arrived that instantly sets off alarms across any infrastructure team:

From: AWS Trust & Safety
Subject: Abuse Report – Suspicion of Unauthorized Vulnerability Scanning from Account 896xxxxxxxxx
Activity: Outbound TCP connections completing full three-way handshakes to port 23 (Telnet) and port 2323 against remote hosts.

Our initial reaction was complete disbelief. We were not operating unpatched Debian servers or legacy EC2 instances. We had no open SSH ports, no bastion servers, and no exposed Jenkins controllers. The application was deployed entirely on AWS App Runner—AWS managed container PaaS.

Under the promise of modern managed cloud, AWS provisions the compute, manages the operating system, orchestrates container scaling, and enforces runtime isolation. Yet, cybersecurity honeypots across Europe and Asia were reporting sustained port scans and banner grabbing originating directly from our cloud resources.

⚡ EXCLUSIVE SRE & KUBERNETES PLAYBOOK

The 970+ Incident Handbook & K8s Runbooks are exclusive to subscribers — unlock for FREE

Get battle-tested production runbooks, AWS architecture blueprints, and zero-downtime CI/CD post-mortems sent directly to your inbox. 100% free, no spam.

2. Act I: The Red Herring – Chasing Ephemeral IP Ghosts

Triage stalled initially because AWS App Runner default egress routes internet traffic through shared regional proxy pools rather than dedicated customer VPC Elastic IPs. Engineers attempting aws app runner egress filtering without dedicated VPC connectors cannot map reported abuse IPs directly to active services, exposing outbound egress control limits where shared multi-tenant infrastructure conceals which container originated malicious traffic.

The AWS abuse report flagged high-volume port scanning originating from shared regional egress proxy endpoints in the AWS Singapore (ap-southeast-1) pool.

Our incident triage playbook began with immediate inventory verification via the AWS CLI:

# Checking all allocated Elastic IPs across the ap-southeast-1 region
aws ec2 describe-addresses \
  --region ap-southeast-1 \
  --query "Addresses[].PublicIp" \
  --output text

# Checking all running EC2 instance public IPv4 addresses
aws ec2 describe-instances \
  --region ap-southeast-1 \
  --filters "Name=instance-state-name,Values=running" \
  --query "Reservations[].Instances[].PublicIpAddress" \
  --output text

The result: Zero matches. The flagged regional egress endpoints did not match any static Elastic IP, dedicated NAT Gateway, or running EC2 instance in our account.

The App Runner Default Egress Blind Spot

This is where many cloud architects hit their first operational surprise with AWS App Runner.

When you deploy a container to AWS App Runner with Default Egress, outbound internet requests do not route through your private VPC. Instead, outbound traffic passes through a shared, multi-tenant AWS regional proxy infrastructure.

Architecture Topology // Default Regional Egress Path
Egress Threat: Critical
Patient Zero

Target Container

AWS App Runner PaaS Service

Runtime: Next.js 15.1.7 (RSC)
Egress: Default Regional NAT
Status: Remote Shell Spawned
Shared Gateway

Regional NAT Pool

Multi-Tenant Egress Infrastructure

Scope: Regional Shared Proxy
Attribution: Shared Multi-Tenant IPs
Isolation: Zero VPC Flow Logs
Abuse Detected

Threat Sensors

Global Honeypots & Security Scanners

Probed Ports: TCP 23 & 2323 (Telnet)
Pattern: High-Rate 3-Way SYN Scans
Trigger: AWS Trust & Safety P1 Flag
Architecture Mode Egress Routing Path IP Attribution VPC Flow Logs Database Isolation Security Grade
Default App Runner Shared Regional AWS NAT Multi-Tenant Shared Pool Disabled (Blind Spot) Public Hostnames Only HIGH RISK
App Runner + VPC (Public) VPC Connector → Public Subnet No Default Gateway Partial VPC Eni Capture Connection Timeouts OUTAGE TRAP
Hardened Private Egress VPC Connector → Private NAT GW Dedicated Elastic IP Full 100% Flow Telemetry Private Subnet Peering HARDENED

Because the abuse report traced outbound packets to the AWS Singapore App Runner regional egress pool, we had two distinct services sharing the exact same regional gateway: a customer-facing Next.js dashboard and an internal micro-service frontend. We needed forensic proof to isolate which container was Patient Zero.

3. Act II: Anatomy of Patient Zero – Unauthenticated React Server Components RCE

Forensic inspection revealed a severe server components deserialization attack exploiting an unauthenticated rsc serialization vulnerability in unpatched Next.js 15.1.7 runtimes. Attackers craft malicious serialized payloads containing prototype pollution gadget chains transmitted via HTTP POST headers, creating unauthenticated rce examples that execute arbitrary shell commands inside Node.js containers without requiring valid session tokens or database credentials.

We pulled CloudWatch application log streams across both container instances to trace raw incoming requests during the abuse window.

In the frontend service logs, the forensic signature was clear:

[Error: RCE_RES]
    at Object.runInternalAction (/app/.next/server/chunks/892.js:14:28)
    at async eval (eval at executeScript (/app/node_modules/next/dist/server/app-render/action-handler.js), <anonymous>:1:34)
    at async processActionRequest (/app/node_modules/next/dist/server/app-render/action-handler.js:412:18)
    at async Server.handleRequest (/app/node_modules/next/dist/server/next-server.js:1145:22) {
  digest: "NEXT_REDIRECT;replace;https://evil-scanner-c2.xyz/drop.sh;307;"
}

The error timestamps matched the exact seconds the third-party abuse reports recorded outbound Telnet handshakes.

The Exploitation Sequence

Our application was locked to next@15.1.7. Recent security vulnerabilities in React Server Components (RSC) serialization allowed malicious actors to craft HTTP POST requests containing serialized JavaScript prototype pollution payloads.

Forensic Kill Chain // Three-Stage Exploitation Sequence
CVSS 9.8 Critical
01
Initial Ingress

Inbound Exploit Injection

POST /_next/data HTTP/1.1
Payload: Serialized RSC Gadget

The attacker discovered the public HTTPS URL and submitted a crafted POST request targeting an RSC action endpoint with a serialized payload designed to hijack Node.js object prototypes.

02
Code Execution

Deserialization & Shell Fork

eval(actionPayload)
Spawn: child_process.exec(/bin/sh)

The payload broke out of the virtualized React execution context, invoking child_process.exec() to pull a lightweight binary scanner from an external staging host into /tmp.

03
Lateral Abuse

Botnet Scanning Deployment

./tmp/scanner -p 23,2323
Egress: High-Bandwidth SYN Burst

The downloaded binary initiated automated high-volume SYN scans against external IP ranges on Telnet ports 23 and 2323, immediately triggering AWS Trust & Safety automated abuse telemetry.

4. Act III: The Band-Aid That Broke Production (Cascading Database Outage)

Remediation backfired when our team attached a custom VPC connector with egress network ACL rules to block outbound Telnet traffic immediately. Because the container reached PostgreSQL using public endpoints, forcing egress through private VPC NAT gateways severed database connections whose security groups lacked the NAT Elastic IP, causing an immediate cascading 500 downtime outage.

Our initial incident response impulse was containment: Sever the container outbound access to prevent AWS from suspending our account.

Because default App Runner egress bypasses your VPC, local Security Groups cannot restrict outbound container packets. To impose network controls, we created an App Runner VPC Connector linked to our private VPC subnets.

1. Applying VPC Network ACL Rules

We updated our VPC Network ACL (acl-053e6828260f5af57):

  • Rule 90: DENY outbound TCP destination port 23 (0.0.0.0/0)
  • Rule 91: DENY outbound TCP destination port 2323 (0.0.0.0/0)
  • Rule 100: ALLOW outbound all traffic (standard egress)

Next, we updated App Runner to route traffic through our custom VPC Connector:

aws apprunner update-service \
  --service-arn "arn:aws:apprunner:ap-southeast-1:896xxxxxxxxx:service/production-web/1234abcd" \
  --network-configuration "EgressConfiguration={EgressType=VPC,VpcConnectorArn=arn:aws:apprunner:ap-southeast-1:896xxxxxxxxx:vpcconnector/prod-vpc-conn/1}"

2. The Cascading Failure: PostgreSQL Connection Drops Dead

Within minutes of the deployment reaching RUNNING status, our uptime monitors sounded P1 alerts across the platform:

SequelizeConnectionError: connect ETIMEDOUT postgres.internal.vpc:5432
    at Client._connect (/app/node_modules/pg/lib/client.js:311:13)
    at Connection.connect (/app/node_modules/pg/lib/connection.js:17:17)
    at Pool._createResource (/app/node_modules/generic-pool/lib/genericPool.js:237:15) {
  name: "SequelizeConnectionError",
  parent: Error: connect ETIMEDOUT
}
The Architectural Trap of VPC Egress Shift

Under default egress, the Next.js container connected to Amazon RDS using its public endpoint hostname. When we switched egress to our VPC Connector, all outbound internet traffic was forced through our VPC NAT Gateway. The RDS database security group had only whitelisted the office IP and individual developer CIDRs—it had never whitelisted the VPC NAT Gateway Elastic IP. Every database query timed out.

3. The Realization: Egress Filtering is a Band-Aid

Even after restoring database connectivity by configuring private VPC endpoints for RDS, we confronted the hard truth of our mistake.

Blocking outbound Telnet ports only prevented the container from scanning external hosts. It did nothing to patch the unauthenticated RCE on port 443. The attacker still had root execution inside the container. They could steal environment variables, dump database credentials, or exfiltrate customer records via HTTPS port 443 without triggering our port 23 ACL block.

5. Act IV: The Permanent Fix & Hardening Sequence

Executing robust nextjs rce containment steps requires immediate framework dependency patching, credential invalidation, and container runtime isolation. Production teams must upgrade Next.js to patched releases, rotate database connection strings and environment secrets, purge compromised App Runner instances, and enforce non-root container user permissions to prevent compromised runtimes from writing persistent payloads or scanning external hosts.

True incident remediation required tackling the vulnerability at the root while locking down the runtime environment.

Layer Vulnerable State Production Remediation
Application Layer next@15.1.7 (unauthenticated RSC deserialization bug) Upgraded to next@15.2.0+ with hardened action validation
Secret Management Plaintext env variables accessible in compromised shell Immediate rotation of database credentials, API keys, and IAM roles
Network Egress Default Egress over shared multi-tenant public IPs VPC Connector with private RDS endpoints and strict security groups
Container Runtime Writable root filesystem; processes run as root Enforced non-root user (USER nextjs:nodejs) and read-only container rootfs

Upgrading the Framework Dependency

We bumped the framework version and verified clean dependency trees across all lockfiles:

# Update dependencies in package.json
npm install next@latest react@latest react-dom@latest

# Audit and verify zero high/critical CVEs
npm audit --audit-level=high

# Rebuild container with non-root security context
docker build -t production-web:patched .

6. DevSecOps Architectural Rules: The Managed Cloud Reality Check

Operating modern cloud containers safely requires aligning engineering practices with the managed cloud responsibility model across all operational tiers. Infrastructure teams must enforce automated ci/cd vulnerability gates and comprehensive ci/cd container image checks before promoting builds, ensuring perimeter network defenses never substitute for runtime dependency security, immutable file systems, and strict zero-trust secret management in production.

This incident offers three non-negotiable rules for any engineering organization shipping containerized web applications:

Rule 1: The Cloud Shared Responsibility Model Still Applies

Whether you run Amazon ECS, AWS App Runner, Google Cloud Run, or Azure Container Apps, managed infrastructure does not equal managed application security.

  • The Cloud Provider Job: Securing the physical data center, hardware hypervisor, host kernel, and PaaS control plane.
  • Your Job: Securing container dependencies, application framework code, secret lifecycles, and inbound request deserialization.

To inspect runtime containment and security boundaries for AI-driven pipelines, explore our production architecture for AI agent guardrails and runtime defense.

Rule 2: Never Rely on Network Perimeter Alone

Perimeter firewalls, Network ACLs, and Web Application Firewalls (WAF) provide defence-in-depth, but they cannot replace application-layer hardening. An unauthenticated RCE on port 443 will tunnel right through perimeter firewalls. Enforce defence-in-depth at the container level:

  • Run containers as non-root users with minimal Linux capabilities (drop: ALL).
  • Make the root container filesystem read-only (readOnlyRootFilesystem: true).
  • Mount temporary write volumes (/tmp) with noexec, nosuid flags.

Rule 3: Enforce Automated Vulnerability Gates in CI/CD

Modern application vulnerabilities are weaponized within hours of public disclosure. Automated dependency scanners (Dependabot, Snyk, Trivy) must run as blocking CI/CD pipeline gates on every pull request, failing builds whenever critical CVEs are detected.

For related incident playbooks and forensic case studies, review our breakdown of the Binance infrastructure hack forensic breakdown and our analysis of Black October critical vulnerabilities.

Next.js RCE Vulnerability: Key Takeaways

A production-ready rce incident postmortem checklist ensures engineering organizations address root application flaws rather than relying on superficial network containment band-aids. By understanding how nextjs rce hijacked our aws container, DevOps teams can establish automated dependency scanning, private VPC database routing, and verified incident runbooks that protect managed serverless containers against emerging zero-day vulnerabilities.

Essential takeaways from this production postmortem include:

For infrastructure teams managing high-reliability cloud architectures, explore our real-world tutorials on Deploying Kubernetes on AWS, reducing AWS infrastructure costs safely, and automating DevOps incident runbooks safely.

Frequently Asked Questions

Direct answers to frequent engineering questions regarding AI coding agent disruptions, entry-level career outlooks, computer science degree value, and the changing landscape of software development roles in production environments.

Can a managed container service like AWS App Runner protect against application-level RCE?

No. Managed container services guarantee infrastructure availability, host OS patching, and hardware isolation. They cannot inspect or sanitize the internal runtime logic of your application framework. Under the Cloud Shared Responsibility Model, securing dependencies and sanitizing incoming deserialization payloads remains entirely your responsibility.

Why does AWS App Runner default egress use shared regional public IPs?

To simplify deployment for developers without requiring a pre-configured VPC, subnets, or NAT Gateways. In default egress mode, App Runner routes internet traffic through AWS shared regional proxy pool. To control outbound traffic or connect privately to databases, you must attach a VPC Connector.

Why did moving App Runner to VPC egress cause database connection timeouts?

Because the container was configured to reach the database using its public endpoint. Once attached to the VPC connector, outbound internet traffic routed through the VPC NAT Gateway. The RDS security group did not whitelist the NAT Gateway Elastic IP, causing incoming packets to be dropped. The solution is connecting to RDS via its private VPC endpoint.

What immediate steps should be taken if a container suffers an RCE compromise?

First, isolate or pause the vulnerable service to stop active exploitation. Second, invalidate and rotate all secrets, database credentials, and API keys accessible from the container environment. Third, patch the vulnerable framework dependency and redeploy from a clean, hardened base image. Finally, audit cloud audit logs (AWS CloudTrail) for unauthorized IAM actions during the dwell time.

How Next.js RCE hijacked our AWS container in production?

The attack leveraged an unauthenticated React Server Components serialization vulnerability in Next.js 15.1.7. An attacker dispatched crafted HTTP POST requests with prototype pollution gadget chains, achieving arbitrary remote code execution inside the Node.js container and initiating unauthorized outbound Telnet port scans across external network endpoints.

Naveed Ahmed

Naveed Ahmed (Kumbhar)

Senior DevOps & Cloud Engineer with 10+ years specializing in AWS, Kubernetes, Platform Engineering, SRE incident response, and autonomous AI infrastructure agents.

Passionate about cloud architecture & systems engineering? Connect on LinkedIn →