How to prevent shell script injection on my local webpage?
<p>I have an openwrt router that I use as a local webserver and I created a webpage to dial USSD on my 3G modem, the script looks like this:</p>

<pre><code>&lt;html&gt;
&lt;title&gt;CHECK USSD&lt;/title&gt;
&lt;body&gt;
&lt;?php
if($_POST['send']){
    $ussd=$_POST['ussd'];
    exec('ussd.py '.$ussd,$out);
    echo "Result: ".$out[0];
}
?&gt;
&lt;form action="" method="post"&gt;
USSD :&lt;input type="text" autofocus name="ussd" size="14" value=""&gt;
&lt;input name="send" type="submit" value="Send Ussd"&gt;
&lt;/form&gt;
&lt;/body&gt;
&lt;/html&gt;
</code></pre>

<p><code>ussd.py</code> is the python script that I use to check USSD. The problem is that when a user tries to input some kind of script in the input box, like: <code>$(echo "hacked" &gt; /www/index.html)</code> or <code>$(rm -fr /root/*)</code> those scripts get executed as well. So people can easily hack my router. How can I prevent that from happening ?</p>

<p>The command you're looking for is <code>escapeshellarg()</code> so that your string is treated as a single argument.</p>

<pre><code>$pattern = '/Some regex that matches your potential inputs/';

if (preg_match($pattern, $ussd)) {
   exec('ussd.py '.escapeshellarg($ussd),$out);
} else {
   //throw error / response to user
}
</code></pre>

<p>Generally speaking though, executing directly from user input is not considered safe. Hence, find a regex that corresponds to a pattern in your potential input commands, and ensure that it matches before proceeding (You have specified that hardcoded commands are not an option).</p>

php python shell