Reputation: 1049
I'm trying to run a shell script using php exec.
The thing is - this isn't very secure as I am posting to it via a html text box i.e.
<?php
$output = shell_exec ('whois '.$_POST['domain']);
echo "<pre>$output</pre>";
?>
The thing is... if a user entered | rm -rf *
It would delete everything in the folder.
Is there a secure way of executing shell scripts and preventing this from happening?
Thanks
Upvotes: 1
Views: 1447
Reputation: 15706
There is always a function to escape user data being passed to another system. In the case of shell commands, there is escapeshellarg. No matter what other kind of validation you do on user input, it is always a good idea to escape arguments just before you pass them to the shell function.
For example:
$domain_arg = escapeshellarg( $_POST['domain'] );
$output = shell_exec( 'whois ' . $domain_arg );
Upvotes: 1
Reputation: 2600
you want to do a whois. so you need to validate if it containes only the parts you want. in your case a domain and nothing else.
if (preg_match('/^(?:[-A-Za-z0-9]+\.)+[A-Za-z]{2,6}$/', $_POST['domain']))
{
$output = shell_exec('whois ' . $_POST['domain']);
echo "<pre>$output</pre>";
}
else
{
echo "stop trying to make my server annoyed";
}
Upvotes: 0