I am rewriting my API for my app in PHP and am using the request structure
http://example.com/controller/function
and my API breaks up the request_uri into:
array(
0 => "controller",
1 => "function"
);
and executes the requested function via the following code.
//Build the file name
$fileName = ('../controllers/' . $endpoint[0] . '.php');
//Look for the file that is being requested
if(!file_exists($fileName)){
echo json_encode( StatusCodes["no_endpoint"] );
die();
} else {
include_once($fileName);
}
//Does the function exist?
if(!function_exists($endpoint[1])){
echo json_encode( StatusCodes["no_function"] );
die();
}
//Import the API settings to get all the keys necessary
include_once('../includes/ApiSettings.php');
//Include the common functions. Done here so the user can't bypass function_exists checks
include_once('../includes/CommonFunctions.php');
//Finally, execute the requested function
echo json_encode($endpoint[1]());
as one of my colleagues has pointed out to me, executing through echo json_encode($endpoint[1]());
can lead to people getting out of the webroot directory, or echoing system information back, for instance, if they hit the endpoint http://example.com/controller/phpinfo
. Which is a MAJOR security issue.
What method should I be using instead, or how can I prevent people from doing remote code execution and causing all kinds of problems.
Create an array of functions that are acceptable to call and use it as a whitelist. Check against that and not against every function that exists.