Hey guys! It's been a few months since my last article, but here is my follow up post describing how to defend against Command Injection. We know that this vulnerability is a result of poor coding practices. In order to prevent system commands being passed from the web application to the operating system we can implement a few things: input validation, least privilege and web shell detection.

Input validation

Input validation is the verification of user data before it is passed through an application. This process ensures that a user can only input a limited range of data. One common way is to create a white-list of commands that have been pre-approved that should only be used with that application. Another strategy is to define a list of regular expressions that are allowed to be used in the application. Since we know only domain names should be used we can apply a regular expressions list similar to this /a-zA-Z0-9/. This allows only lowercase and uppercase letters A through Z as well as numbers 0 through 9 to be acceptable as user input.

Least privilege

The principle of least privilege is when a user of a computer system possesses the bare minimum functions to perform their necessary tasks. For example, a regular user on a Windows system should not have the ability to open a command prompt with administrative privileges; only a System or Network Administrator should because that is what their job entails. For this web application the www-data user should have not be allowed to execute system commands. Alternatively, you could white-list a single system command (nslookup) since that is the only function of the web application. All other system commands should be blocked in order to reduce the attack surface.

Web Shell Detection

One strategy to detect web shells on your web server would be File Integrity Monitoring (FIM). FIM is a security control establishes a baseline of specific files on the system and then looks for any deviation from that baseline. Security teams will be alerted on any anomalies and can be further analyzed to see if any malicious activity is present or not. SANS has compiled a list of file paths for both UNIX and Windows systems where you can deploy FIM.

One final thing to look for is suspicious shell commands. If you're employing least privilege techniques then it would be strange to see users on a web server running cat /etc/passwd or cat /etc/shadow conducting password reconnaissance. To understand what commands to look for, Mubix has a list of post-exploitation commands for Linux here.

Resources