0

I want to filter user input like this:

$data = file_get_contents('php://input');

if ($data != null && $data !=='') {
    $parsedData = json_decode($data, true);
}

// find quickmodule name
$moduleName = $_GET['module'];

// validate name
if (! preg_match("/^[0-9a-z]+$/i", $moduleName)) {
    die("Invalid quickmodule name");
}

// check if exists
$modulePath "/quick/".$moduleName.".php";
if (file_exists($modulePath)) {
    require_once($modulePath);

Does this solution really save me, and is it possible to bypass it in modern PHP? Tricks with newline did not work.

if (! preg_match("/^[0-9a-z]+$/i", $moduleName)) {
    die("Invalid quickmodule name");
}
schroeder
  • 123,438
  • 55
  • 284
  • 319

1 Answers1

0

I was not able to bypass the regex as it is only allowing alphanumeric characters, which is a decent approach. Alternatively, if you know the files that are going to be accessed, you can use a whitelist approach as well, it will eliminate the possibility of unknown input handling. Sample code can be:

  $allowedModules = array('module1.php', 'module2.php', 'module3.php');
  $moduleName = $_GET['module'];

  if(in_array($moduleName, $allowedModules) && file_exists($moduleName)){
    require_once ($moduleName);
  }else{
    //output error
  }
Syed Anas
  • 91
  • 3