Sometimes a web application takes user input and executes corresponding commands in the server and displays the output. A Shell Injection Attack or Command Injection Attack is an attack in which an attacker takes advantage of vulnerabilities of a web application and executes arbitrary command in the server for malicious activities.
How is Command Injection Attack perpetrated
Suppose, a web application takes name of a file as input from a user and displays it contents. And, the web application has implemented that with the following piece of PHP code :
print(Please specify the name of the file ) ;
$file = $_GET['filename'] ;
system(“cat $file”) ;
So, if a user gives an input 'profile.txt', corresponding file will be displayed.
But, suppose an attacker gives an input 'profile.txt ; ls ;'. It will list all files in the directory where profile.txt is kept.
Or even worse, the attacker can give input 'profile.txt; rm -rf /;” and this will delete all files in the root directory.
The following are the most common operators used to exploit this vulnerability :
- <command 1> ; <command 2> - to execute sequential command
- <command 1> | <command 2> - to set the output of command 1 to some malicious command command 2
- command 1 `command 2` - to set the output of command 1 as arguments of command 2
- command 1 $(command 2) – to set the output of command 1 as arguments of command 2
- command 1 && command 2 – to execute command 2 if and only if command 1 is successful
- command 1 || command 2 – to execute command 2 in case command 1 is not successful
- command 1 > filename – to overwrite filename with output of command 1
- filename 1 < filename 2 – to replace contents of filename 1 with that of filename 2
Countermeasures for Shell Injection or Command Injection Attacks
We can take a couple of steps to prevent this attack.
- Carefully sanitize all user input data in the web application.
- Strip certain characters like ';', '&', '|' etc from user input data.
- Limit the length of user input data.
- Check the validity of user input data type.
- It is always advisable to include filtering functions before executing the command. In PHP, escapeshellarg, escapeshellcmd may solve the purpose.
This was another article to inform you about one more recent vulnerability of web applications. Hope you liked it.