Skip to main content

Remote Code Execution (RCE)

Remote Code Execution

Table of Contents

Quick Answer

RCE stands for remote code execution: a vulnerability that lets an attacker run code of their choice on a system they reach over a network. It happens when untrusted data reaches something that can turn data into behaviour, such as an interpreter, a deserializer, an upload directory that executes files, or memory-unsafe native code. The attacker gets the permissions of the affected process. Prevent it by keeping data away from those operations, patching dependencies and runtimes, running with least privilege, and watching for processes and connections the application should never create.

This defensive guide explains what RCE means, how it differs from the terms used alongside it, and which weaknesses cause it. Three Java examples each show the fault, a harmless test that detects it, and the fix. They are not exploit material: there are no payloads, exploit chains or ways around protections here.

What does RCE mean?

In cyber security, RCE means remote code execution. Each word matters:

  • Remote: the attacker does not need an account on the machine or physical access to it. They send something to the software over a network, directly or through another system that passes it on.
  • Code: what runs is chosen by the attacker. It might be machine code, a script, an expression, an operating system command, or existing methods in the application called in an order nobody intended.
  • Execution: it actually runs, inside the affected process or started by it, with that process's identity, files, secrets and network access.

RCE describes an outcome, not a single kind of bug. That is why there is no one CWE number for it. The weaknesses that lead to it include CWE-94 (code injection), CWE-78 (operating system command injection), CWE-434 (unrestricted file upload), CWE-502 (deserialization of untrusted data) and CWE-122 (heap-based buffer overflow). All five are in the 2025 CWE Top 25.

You will also see unauthenticated or pre-authentication RCE, which means no login is needed and is the most urgent form. Authenticated RCE needs valid credentials first, which is less protection than it sounds on any service where people can register themselves or where passwords are reused.

How remote code execution happens

Almost every RCE follows the same path. Untrusted data travels from a source, where it enters the system, to a sink, an operation able to change what the program does.

StageWhat happensWhere to break it
1. Input arrivesA request body, header, token, filename, queue message, imported file or log value carries data the attacker controls.Reduce what is exposed. Accept only the types, sizes and values you expect.
2. It reaches a dangerous sinkThe data is passed to an interpreter, deserializer, file writer, class loader or native decoder.Remove the sink, or make the choice of behaviour yours instead of the input's.
3. Code runsThe sink treats the data as instructions, or is corrupted into running them.Patch the component. Harden the runtime.
4. The impact spreadsThe code reads secrets, changes data, installs persistence or connects to other systems.Least privilege, restricted outbound traffic, separated networks and monitoring.

The source and the sink can be far apart. A value saved to a database today may be evaluated by a report job next week, and a harmless-looking header may be executed by a logging library that the developer never thought of as a parser. Trace data through storage and dependencies as well as through your own methods.

What happens after stage 3 depends on the process. A service running as an unprivileged user in a container with no outbound network is a serious incident. The same bug in a service running as an administrator with cloud credentials can be the whole organisation. Attackers who land with limited rights usually try privilege escalation next.

These four terms are often used as if they were the same. Two of them name a result and two name a cause.

TermResult or causeWhat it means
Arbitrary code execution (ACE)ResultThe attacker can run code of their choice. It may need local access, for example opening a crafted file on that machine.
Remote code execution (RCE)ResultArbitrary code execution that can be triggered over a network.
Code injectionCause (CWE-94)Input becomes part of code that the application's own language or expression engine evaluates.
Command injectionCause (CWE-78)Input changes an operating system command that the application starts.

The distinction is practical. An advisory that says "RCE" tells you how bad the result is. The weakness behind it tells you what to fix, and where else in your code to look for the same mistake.

Common causes of RCE

1. Injection into an interpreter

Script engines, template engines, expression languages and shells exist to execute text. When input becomes part of that text, the sender becomes a programmer of your application. SQL injection belongs to the same family and can reach code execution when the database account is allowed to run programs or write files. The general habit behind all of them is covered in input validation attacks, but validation alone is not the cure: the cure is keeping data and instructions separate.

2. Unsafe deserialization

Formats such as Java serialization and Python pickle describe objects to construct, not just values. Reading them can invoke methods of classes that are already installed with the application. Oracle's documentation calls deserializing untrusted data inherently dangerous, and the danger does not depend on your own classes being malicious. Libraries that map JSON, XML or YAML to objects carry a similar risk when they are configured to let the document name the class.

3. File upload

An upload becomes RCE when a file ends up somewhere that executes it: a script in the web root, an archive in a deployment directory, a library on a load path, a template in a folder the engine renders. A file can also attack the software that processes it, such as an image converter or a document parser. An XML upload brings XXE with it, which usually leaks data and in some configurations goes further.

4. Memory corruption

In C, C++ and other native code, a buffer overflow or use-after-free can overwrite the data that decides what runs next. Applications written in memory-safe languages inherit this risk through the runtime, native libraries and decoders beneath them.

5. Vulnerable dependencies and runtimes

The vulnerable sink is often code you did not write. All three incidents later on this page were in widely used components: a web framework, a logging library and the Java runtime itself. When such a flaw is exploited before a fix exists it is a zero day, but much of the damage is done afterwards, on systems that had a patch available and had not applied it.

CauseWeaknessOWASP Top 10:2025First thing to look for
Code and command injectionCWE-94, CWE-78, CWE-917A05 InjectionEvaluation or process calls built from variables
Unsafe deserializationCWE-502A08 Software or Data Integrity FailuresObject readers on data from outside the process
File uploadCWE-434A06 Insecure DesignClient filenames used in paths, storage inside the web root
Memory corruptionCWE-122, CWE-787Outside the main web categoriesNative parsers and decoders handling untrusted bytes
Vulnerable componentCWE-1395A03 Software Supply Chain FailuresComponents with no owner or no supported version

Java examples with fixes

The three examples below were compiled and run on Java 21, with imports left out for length. Each test uses a harmless value that only proves whether untrusted input reaches the sink. Run such tests only against code you own or are authorised to test.

Unsafe deserialization

The fault. The method looks type-safe because of the cast. By the time the cast runs, the stream has already decided which class to create.

record Order(long id, int quantity, long unitPrice) implements Serializable {}

static Order readUnsafe(InputStream body) throws IOException, ClassNotFoundException {
    try (var in = new ObjectInputStream(body)) {
        return (Order) in.readObject();   // the cast runs after the object is built
    }
}

How to detect it. Search for ObjectInputStream and trace where its bytes come from. Find Security Bugs reports this pattern as OBJECT_DESERIALIZATION. In a unit test, send a harmless object of the wrong type. A ClassCastException is evidence of the fault, because it means the wrong object was built first.

Test input: a serialized java.util.Date where an Order is expected

readUnsafe -> ClassCastException      the Date was created, then the cast failed
readFixed  -> InvalidClassException   filter status: REJECTED

The fix. The best fix is not to use native serialization for untrusted data: accept JSON bound to a fixed type, with polymorphic type handling off. Where the format cannot change yet, set an allow-list filter before the first read. It names the permitted classes, rejects everything else and limits size and depth.

static Order readFixed(InputStream body) throws IOException, ClassNotFoundException {
    var filter = ObjectInputFilter.Config.createFilter(
        "maxbytes=4096;maxdepth=4;maxrefs=50;maxarray=0;"
        + Order.class.getName() + ";java.lang.Record;!*");
    try (var in = new ObjectInputStream(body)) {
        in.setObjectInputFilter(filter);
        return (Order) in.readObject();
    }
}

Expression evaluation on user input

The fault. A pricing feature accepts a rule as text and evaluates it with the Spring Expression Language. The feature wanted arithmetic. The language also offers methods, constructors and type references.

static Object priceUnsafe(Order order, String rule) {
    // rule comes from the request
    return new SpelExpressionParser().parseExpression(rule).getValue(order);
}

How to detect it. Search for parseExpression and other evaluators whose argument is not a constant. Find Security Bugs reports this one as SPEL_INJECTION. In a test, plain arithmetic is enough: if it comes back calculated, the input is being executed.

Test input: the text "6 * 7" where a rule name is expected

priceUnsafe -> 42                         the input was evaluated
priceFixed  -> IllegalArgumentException   Unknown pricing rule

The fix. Let the user choose a name and keep the behaviour in code. Switching to Spring's SimpleEvaluationContext is not enough. Spring's documentation says that restriction is best effort and that evaluating expressions from untrusted sources should generally be avoided whichever context is used.

static final Map<String, ToLongFunction<Order>> RULES = Map.of(
    "standard", o -> o.unitPrice() * o.quantity(),
    "half-price", o -> o.unitPrice() * o.quantity() / 2);

static long priceFixed(Order order, String ruleName) {
    var rule = RULES.get(ruleName);
    if (rule == null) throw new IllegalArgumentException("Unknown pricing rule");
    return rule.applyAsLong(order);
}

File upload into a served directory

The fault. The client chooses the filename, so it chooses the extension and can influence the path. The server then stores the file where it serves, and may execute, content.

static void saveUnsafe(Path webRoot, String filename, InputStream body) throws IOException {
    // filename comes from the client, webRoot is served by the application server
    Files.copy(body, webRoot.resolve(filename), StandardCopyOption.REPLACE_EXISTING);
}

How to detect it. Follow every uploaded filename to the file API that uses it. Find Security Bugs flags tainted names as FILE_UPLOAD_FILENAME and writes as PATH_TRAVERSAL_OUT. In a test, upload plain text with a server-side extension and check where it lands. There is no need for the file to contain code.

Test input: a harmless text file named canary.jsp

saveUnsafe -> stored in the web root as canary.jsp
saveFixed  -> IllegalArgumentException   Expected a PNG up to 2 MB

The fix. Generate the name on the server, limit the size, allow only the types you need and store the file outside the web root in a directory that cannot execute. A signature check does not prove a file is safe, so re-encode images where you can, and serve files through a handler that sets the content type and X-Content-Type-Options: nosniff.

static final int MAX_BYTES = 2 * 1024 * 1024;
static final byte[] PNG = {(byte) 0x89, 'P', 'N', 'G', 13, 10, 26, 10};

static String saveFixed(Path privateDir, InputStream body) throws IOException {
    byte[] data = body.readNBytes(MAX_BYTES + 1);
    if (data.length > MAX_BYTES || data.length < PNG.length
            || !Arrays.equals(data, 0, PNG.length, PNG, 0, PNG.length)) {
        throw new IllegalArgumentException("Expected a PNG up to 2 MB");
    }
    String id = UUID.randomUUID() + ".png";
    Files.write(privateDir.resolve(id), data, StandardOpenOption.CREATE_NEW);
    return id;
}

Real incidents

Equifax and Apache Struts, 2017

CVE-2017-5638 was a flaw in the way the Apache Struts 2 multipart parser handled errors: a malformed upload header could end up evaluated as an expression. It scored 9.8, and Apache shipped fixes in March 2017.

Equifax's former chief executive told Congress that the company received the notification on 8 March, that the patch was not applied to a dispute portal, and that a scan around 15 March failed to find the vulnerable system. Suspicious activity was detected on 29 and 30 July, 76 days after the breach began. The number of people affected given at that October 2017 hearing was 145.5 million. The lesson is about inventory: a patch process only protects the systems it knows about.

Log4Shell, 2021

CVE-2021-44228 scored 10.0. Apache Log4j 2 resolved lookups inside the values it logged, including JNDI lookups able to load code from a remote server. Writing an attacker-controlled string to a log was enough on affected configurations, and applications log such strings all day.

CISA added it to its Known Exploited Vulnerabilities catalog on 10 December 2021, the day NVD published it. The first fix, 2.15.0, was incomplete for some non-default configurations and received its own CVE, so teams had to patch again. The lesson is that any library can be a sink, and that you need to be able to answer "where do we run this version?" in hours, including for dependencies of dependencies.

Java4Shell, 2026

Status checked on 22 November 2026. CVE-2026-114938, fixed on 17 November 2026, is a heap-based buffer overflow in the hardware-accelerated Base64 decoder of the HotSpot Java virtual machine. Malformed input can make the native routine write past the end of its output. The result is memory corruption and crashes, and under some conditions unauthenticated RCE. Oracle scores it 8.1, High, with high attack complexity.

According to CERT-EU, exposure needs all three of these: an x86-64 processor with particular AVX-512 features (ARM64 is not affected), the Base64 intrinsic switched on, which is the default on such processors, and attacker-controlled Base64 reaching the decoder. Basic authentication, JWT, SAML messages and cookies are common routes, several of which are decoded before any login succeeds.

Java lineAffectedFixed in
Oracle Java 8 performance builds8u511-perf8u513-perf
1717.0.6 to 17.0.2117.0.21.1
2121.0.13 and earlier21.0.13.1
2525.0.5 and earlier25.0.5.1
2727.0.1 and earlier27.0.1.1

Other distributions publish on their own schedules and bundled runtimes need the product vendor's update, so check both. To see what a service runs:

# the build each service runs (check inside the container, not on your laptop)
java -version

# whether the affected Base64 intrinsic is switched on
java -XX:+UnlockDiagnosticVMOptions -XX:+PrintFlagsFinal -version | grep UseBASE64Intrinsics

Update, rebuild container images and restart every JVM. If you cannot update yet, CERT-EU gives -XX:+UnlockDiagnosticVMOptions -XX:-UseBASE64Intrinsics as a temporary mitigation, which also needs a restart. On the date checked, the CVE was not in CISA's Known Exploited Vulnerabilities catalog and we found no confirmed report of exploitation. That can change, so follow the advisories in the sources.

An unsupported Java release makes this kind of week much harder, because there may be no fixed build to move to. If that is your position, Pashyaa's fixed-price Java upgrade work covers getting back onto a supported line.

How to detect RCE

Detection has three separate questions: could our code allow it, do we ship a component that allows it, and is it happening now?

In code

Start with an inventory of sinks. This search is crude but fast, and every result needs an answer to the question "who controls this value?"

grep -rnE "ObjectInputStream|XMLDecoder|parseExpression\(|ScriptEngine|Runtime\.getRuntime|ProcessBuilder|getOriginalFilename\(" src/

Then add static analysis that follows data from source to sink, and dynamic testing in a test environment for what only appears when the application runs. Our guide to SAST and DAST explains where each fits. Keep the harmless tests from the examples as regression tests.

In dependencies

  • Generate a software bill of materials for each build and keep it with the release, so that a new advisory becomes a search.
  • Scan the resolved dependency tree, not just the libraries you declared. mvn dependency:tree shows what a Maven build really contains.
  • Scan the built container image too. The Java runtime and operating system libraries are not in your build file.
  • Put anything in CISA's Known Exploited Vulnerabilities catalog at the front of the patch queue, whatever its score.

At runtime

SignalWhy it mattersWhere to see it
The application starts a shell or an unexpected child processMost web and API services never need to. It is one of the clearest signs.Endpoint detection, audit logs, container runtime security
New outbound connectionsInjected code often fetches more code or calls back, as in a reverse shell.DNS, proxy and firewall logs
New or changed files in application directoriesWeb shells and other persistence have to be written somewhere.File integrity monitoring
Rejected or unexpected classes during deserializationSomeone is sending objects the service does not use.Filter logging, or the jdk.Deserialization Flight Recorder event, which is off until you enable it
JVM crashes with native framesFailed memory corruption often looks like instability.hs_err_pid files and restart counts
Use of service credentials from a new placeThe code may already have read the secrets and left.Cloud, database and identity provider logs

MITRE ATT&CK records the entry as T1190, Exploit Public-Facing Application, and the web shell that often follows as T1505.003, which is useful when you map these signals to existing alerts.

How to prevent RCE

No single control covers every cause. The first three below remove the opening and the last three limit what an opening you missed is worth.

1. Do not turn data into code

Remove eval, script engines and expression evaluation from paths that handle untrusted data. Map input to a fixed set of operations. Prefer a library call to starting a process. Use data formats that cannot name a class to construct.

2. Constrain every input and parser

Validate type, size and allowed values on the server. Set limits before parsing, disable parser features you do not use, such as external entities and polymorphic types, and treat filenames, headers, tokens and queue messages as input. The OWASP Top 10 checklist is a useful pass before release.

3. Patch components and runtimes as one system

Give every service an owner, stay on supported lines of the language, framework and base image, and automate update pull requests. Rehearse the emergency path so that rebuilding and restarting every service takes hours. A patched package that a running process has not loaded protects nothing.

4. Run with least privilege

Use a non-root account, a read-only file system where possible and only the database and cloud permissions that one service needs. Keep compilers, shells and package tools out of production images. Give each service its own secrets so that one compromise does not expose all of them.

5. Restrict what the server can reach

Deny outbound traffic by default and allow the destinations the service uses. Separate it from administration interfaces and from unrelated databases. Many RCE chains, Log4Shell's classic route among them, need the server to fetch something from outside.

6. Use filters as a bridge, not a destination

Web application firewall rules, feature switches and JVM options can shorten exposure while a fix is tested. Record each one with an owner and a removal date, and still ship the fix.

What to do if you suspect RCE

Assume that everything the process could read has been read, then work in this order. NIST SP 800-61 Revision 3 gives the wider incident response framework.

  1. Start the incident process. Name a lead, record times and actions, and use a communication channel the affected systems cannot read.
  2. Isolate without destroying evidence. Cut network access before you delete or reimage anything. Preserve logs, the disk and, where you can, memory and the container.
  3. Find the entry and the window. Identify the vulnerable path and the earliest sign of use. Check every other instance running the same version.
  4. Rotate secrets from a clean machine. Include database passwords, API keys, signing keys, cloud credentials and tokens the process held.
  5. Rebuild from trusted sources with the fix. Cleaning a host where unknown code has run does not prove it is clean.
  6. Check for spread and meet reporting duties. Review the systems that service could reach, and involve legal or compliance early, because some reporting deadlines are measured in hours.
  7. Close the class of bug. Search for the same sink elsewhere and add the test that would have caught it.

Developer review questions

  • Can any untrusted value reach an evaluator, template source, shell or process call?
  • Does any data from outside the process go to a deserializer that can choose classes?
  • Can a client influence the name, type or location of a file the server writes?
  • Which native decoders, including those in the language runtime, see data before authentication?
  • Could we list every service running a named library or Java build today?
  • Is every runtime on a supported line, and is the running build the patched one?
  • What could this process read, write and reach if its code were replaced?
  • Would an unexpected child process or outbound connection raise an alert?
  • Does each past fix have a regression test?
  • Are these tests run only on systems we are authorised to test?

FAQs

Remote code execution means someone who is not at your computer can make it run instructions they chose, usually by sending data over the network to software with a flaw. The instructions run with the permissions of that software, so they can do whatever it can do: read its files and secrets, use its database connection and reach the systems it can reach.

No. RCE is a capability that a vulnerability gives an attacker, and malware is software. The two often appear together, because an RCE flaw is a convenient way to install ransomware, a web shell or a cryptocurrency miner, but a system can have an RCE vulnerability with no malware on it. Removing malware without fixing the flaw leaves the way in open.

RCE is the ability to run code on a remote system. A reverse shell is one thing that code might do: make the compromised server open an outbound connection that gives the attacker a command prompt. Restricting outbound traffic can stop the reverse shell, but it does not remove the RCE.

No. Command injection is one cause and RCE is the result. In command injection, untrusted input changes an operating system command that the application runs. RCE can also come from unsafe deserialization, expression evaluation, file upload, memory corruption or a vulnerable dependency, none of which needs a shell command in your code.

An RCE that needs no login and no user action scores at or near the top of every CVSS impact and reachability metric. CVE-2017-5638 in Apache Struts scored 9.8 and Log4Shell scored 10.0. The score drops when exploitation needs privileges, user interaction or difficult conditions: Oracle rated Java4Shell 8.1, which is High, because of its high attack complexity. A High RCE on an internet-facing service can still be your most urgent fix.

It can block some known request patterns and buy time while you patch, which OWASP calls virtual patching. It cannot be the fix. A firewall does not know how your application decodes and combines its input, and it may never see data that arrives through a queue, a file or an internal service. Fix the code or the dependency and treat the firewall rule as temporary.

No. Memory safety removes most memory corruption from code written in those languages, but not logic that turns data into code. Java has native serialization and expression languages, and Python has pickle and eval. Both also sit on runtimes and libraries with native code inside, which is how a memory bug like Java4Shell can affect a Java application.

Sources and further reading