1

I wish to implement some user callable functions in my code. I use something like this:

function funcTest(){

    echo "This is test function";

}

if (isset($_GET['cmd']))
{
    $func = "func".$_GET['cmd'];
    $func();

}
else echo "ERROR";

Is the code safe? Can someone execute arbitrary functions? I didn't find a way but I want to be sure as it's an important project.

2

With your current code, users can call any function with zero parameters with starts with func. Although there are probably none in the PHP standard repertoire that may pose a threat when being called, the runtime environment you want to use this in may have such functions. You may also want to change the prefix or composition of the actual function name in the future, which may change the situation radically.

My point is that you don’t do any validation of the function name at all. You should have a list of allowed functions to be called (i. e. a whitelist) and call function_exists to assert that the function actually exists:

if (isset($_GET['cmd']))
{
    $func = "func".$_GET['cmd'];
    if (in_array($func, $allowedFunctions) && function_exists($func))
    {
        $func();
    }
}
2

You do not sanitize your user input, that by itself is considered bad practise. Although I don't think it can be exploited, perhaps the following code is considered more secure.

    <?php

      function x()
      {
         // what ever this function should do
      }

      function y()
      {
         // what ever this function should do
      }

      function z()
      {
         // what ever this function should do
      }

      $func = yourInputFilerFunction($_GET['cmd']);

      switch ($func) {
        case "x":
            x();
            break;
        case "y":
            y();
            break;
        case "z":
            z();
            break;
      }
    ?>

When the parameter 'cmd' is tampered with, the script will not do anything. In your case, the script will try to load a function based on the cmd variable.

If the function does not exist, PHP will throw an error and possibly discloses information about the system such as the internal path.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.