Threats and Vulnerabilities

Command Injection: How it Works and 5 Ways to Protect Yourself

A command injection involves the exploitation of a vulnerable application for the purpose of executing arbitrary commands on its host operating system. These exploits usually target the privileges of a vulnerable application. 

Command Injection: How it Works and 5 Ways to Protect Yourself
Admir Dizdar
May 29, 2022
7 minutes

What is Command Injection?

A command injection involves the exploitation of a vulnerable application for the purpose of executing arbitrary commands on its host operating system. These exploits usually target the privileges of a vulnerable application. 

Typically, it is insufficient input validation that enables actors to exploit the application. When the application passess insecure user-supplied data, such as cookies, forms, or HTTP headers to the system shell, actors can execute malicious commands. 

While code injection and command injection may seem like the same attack, the two differ significantly. Code injection attacks enable actors to add malicious code to the application, which then executes it. Command injection extends the default functionality of an application, tricking it into executing system commands.

This is part of an extensive series of guides about Cybersecurity. You can also read more about Code Injection PHP & Code Injection Examples.

In this article:

How Does a Command Injection Attack Work?

Step 1 

During this stage, threat actors locate a vulnerability in an application which allows them to run malicious operating system commands.

Step 2 

The attacker engineers a command which will cause the application to execute a desired action in the host operating system. They typically use an input mechanism like HTML code, cookies or form fields to inject this command into the application.

Step 3 

The browser interprets the command and it is translated to an operating system command on the host. Threat actors can then execute specific commands on the host machine and the network of the infected system.

Command Injection Example

This example is based on code provided by OWASP. Consider the following C code that prints the contents of a file to the console. It is based on the UNIX command cat.

The problem with this is that it does not validate the input parameter argv. A user can, for example, invoke this code with the following input:

$ ./catWrapper "Story.txt; ls"

The output will display the content of the Story.txt file as expected, but will continue to interpret the rest of the input parameter. The ; character indicates a break, and the text after it is evaluated as a new command. In this case, the ls command will be executed and the program prints the content of the current directory.

The attacker can substitute ls with a string of commands that can perform malicious actions on the host machine. If the catWrapper application is allowed to run with root privileges, for example, this would allow the attacker to take complete control over the host.

This is part of a series of articles about Command Injection.

Command Injection Vulnerabilities

Below are common vulnerabilities, which can potentially expose an application to command injection attacks.

Arbitrary Command Injection

Applications can receive arbitrary system commands directly from end users. Once the application receives the commands, it executes them on the host. This is a common vulnerability that allows command injections.

Arbitrary File Uploads

Applications may allow end users to upload files containing arbitrary file extensions. This vulnerability can allow actors to inject commands once the uploaded files are added to the webroot.  

Server-side Template Injection

Web applications sometimes use server-side templating tools, like Twig or Jinja2, when generating dynamic HTML responses. A server-side template injection (SSTI) vulnerability occurs when user input is insecurely embedded within a template in a manner that allows threat actors to remotely execute code on the server.

XML External Entity Injection

XML external entity (XXE) vulnerabilities occur in applications that use weakly configured XML parsers to parse user-controlled XML input. XXE vulnerabilities can allow threat actors to read arbitrary files from the server and cause Denial of Service (DoS) attacks. 

5 Ways to Prevent Command Injection

Here are several methods you can employ to prevent command injection attacks:

1. Don’t Run System Commands with User-Supplied Input

If you do need to use user-input for a system command, do not call operating system commands directly. Instead, you can use built-in library functions. 

For example, if you are using the Python os library, do not use this command, which directly calls an operating system command: 

os.system(“listdir <directory-path>”)

Instead, use this command, which uses a library function:

os.listdir(“<directory-path>”)

This protects the integrity of existing system files that are included, executed, or parsed by your code. 

Learn more in our detailed guide to code injection example.

2. Use Strong Input Validation for Input Passed into Commands 

You can achieve this by using a whitelist for strings or allowed characters. To enable users to execute arbitrary commands, for example, you can whitelist certain commands, like ls and pwd, to allow only these input strings.

Alternatively, you can whitelist only allowed characters. For example, the regular expression ^[a-z0–9]{1,10}$ allows only numbers and lowercase letters and numbers. It does not allow special characters at all, because actors can use them to manipulate the logic of the command. This expression also limits the length of the input string 10 characters.

You can also escape values that are inserted into operating system commands. Here are several dangerous characters you should escape:

& | ; $ > < ` !

However, this method is often less effective, because threat actors constantly come up with inventive techniques to bypass input validation based on whitelists or blacklists.

3. Use the Principle of Least Privilege

This method strives to provide applications and processes with only the minimum privileges they need for their tasks. The goal is to lower the risk and damage of successful attacks. This way, if threat actors manage to inject commands, they are restricted to the privileges allowed to the application or process. 

4. Update and Patch Applications Often

Make sure you stay up-to-date with patches and updates. This can help keep applications and systems secure and prevent dependencies from introducing command injection vulnerabilities. Additionally, you can use a web application firewall (WAF), which can block suspicious traffic that may include attempted command injection.

5. Test Your Application with Bright

One of the simplest and most effective ways to prevent command injections is to scan your application with a dynamic application security testing (DAST) tool like Bright’. 

Our black-box security testing solution automatically examines your application for OS command injection vulnerabilities. If one is detected, Bright provides remediation guidelines for your developers or SecOps team. No need for lengthy, cumbersome manual testing. 

Learn more about Bright and get started free!

See Additional Guides on Key Cybersecurity Topics

See Additional Guides on Key Cybersecurity Topics

Together with our content partners, we have authored in-depth guides on several other topics that can also be useful as you explore the world of cybersecurity.

AWS Backup

Authored by N2WS

Azure Backup

Authored by N2WS

DAST

Authored by Bright Security

What Our Customers Say About Us

"Empowering our developers with Bright Security's DAST has been pivotal at SentinelOne. It's not just about protecting systems; it's about instilling a culture where security is an integral part of development, driving innovation and efficiency."

Kunal Bhattacharya | Head of Application Security

"Bright DAST has transformed how we approach AST at SXI, Inc. Its seamless CI/CD
integration, advanced scanning, and actionable insights empower us to catch
vulnerabilities early, saving time and costs. It's a game-changer for organizations aiming to
enhance their security posture and reduce remediation costs."

Carlo M. Camerino | Chief Technology Officer

"Bright Security has helped us shift left by automating AppSec scans and regression testing early in development while also fostering better collaboration between R&D teams and raising overall security posture and awareness. Their support has been consistently fast and helpful."

Amit Blum | Security team lead

"Bright Security enabled us to significantly improve our application security coverage and remediate vulnerabilities much faster. Bright Security has reduced the amount of wall clock hours AND man hours we used to spend doing preliminary scans on applications by about 70%."

Alex Brown

"Duis aute irure dolor in reprehenderit in voluptate velit esse."

Bobby Kuzma | ProCircular

"Since implementing Bright's DAST scanner, we have markedly improved the efficiency of our runtime scanning. Despite increasing the cadence of application testing, we've noticed no impact to application stability using the tool. Additionally, the level of customer support has been second to none. They have been committed to ensuring our experience with the product has been valuable and have diligently worked with us to resolve any issues and questions."

AppSec Leader | Prominent Midwestern Bank

Book a Demo

See how Bright validates real risk inside your CI/CD pipeline and eliminates false positives before they reach developers.

Our clients:
SulAmerica Barracuda SentinelOne MetLife Nielsen ABInBev Heritage Bank Versant Health