Command Injection, also known as shell injection, is a web security vulnerability that allows a hacker to execute arbitrary operating system commands on the server that is running an application and fully compromise the application and all of its data. A Hacker can leverage a command injection vulnerability to compromise other parts of the hosting infrastructure exploiting trust relationships to pivot the attack to other systems within the organization.
Consider a shopping application that lets the user view whether a particular item is in stock in a particular store. This information is accessed via a URL. To provide the stock information, the application must query various legacy systems. For historical reasons, the functionality is implemented by calling out a shell command with the product and store ids as arguments. This command outputs the stock status for the specified items which returned to the user. Since the application implements, no defences against command injection, an attacker can submit an adjusted input to execute arbitrary commands with a personalized string separated by the command separator. If the input is submitted in the product id parameter, then the application will execute the command which could return the string as an echo. This signals the hacker that a Command injection vulnerability has been discovered.
How to Prevent Command Injection:
• Never call out to commands from application layer code. In virtually every case there are alternate ways of implementing the required functionality using safer platform APIs.
• If it is considered unavoidable to call out to commands with user-supplied input, the strong input validation must be performed.
• You can validate against a whitelist of permitted values
• You can validate that the input is a number or alphanumeric characters, no other syntax or whitespaces.
• Never tempt to sanitize input by escaping shell metacharacters. In practice, this is too error-prone and vulnerable to be bypassed by a skilled hacker.