PHP - securing parameters passed in a URL
I have an application that makes decisions based on url:
if ( isset($this->params['url']['url']) ) {
$url = $this->params['url']['url'];
$url = explode('/',$url);
$id = $this->Provider->getProviderID($url[0]);
$this->providerName = $url[0]; //set the provider name
return $id;
}
This happens in the cake app, so $ this-> params ['url'] contains the url element. I then use the url element to decide what data to use in the rest of my application. My question is ...
What is the best way to protect this entrance so that people cannot enter something unpleasant?
thank,
source to share
The other comments here are correct, in the AppController beforeFilter check the provider against the providers in your db.
However, if all urls must have a provider string prefix, you are going to extract it from the url incorrectly by looking at $ this-> params ['url'].
This problem is exactly what the router class is, and its ability to pass parameters for an action. Check out the cookbook man page at http://book.cakephp.org/view/46/Routes-Configuration . You can try something like:
Router::connect('/:provider/:controller/:action');
Throughout the tutorial, you'll also see the ability to validate a vendor parameter in a route with a regex - if you have a small specific list of known vendors, you can hardcode them into a regex of the route.
By creating a route that grabs that part of the url, it is instantly available in $ this-> params ['provider'], but even better than the fact that the html helper link () method automatically builds properly formatted urls. eg
$html->link('label', array(
'controller' => 'xxx',
'action' => 'yyy',
'provider' => 'zzz'
));
Returns a link like / zzz / xxx / yyy
source to share
I would reiterate Carsten's comment: define "something unpleasant"
What do you expect from the parameter? If you expect it to be a URL, then use a regular expression to validate the URLs. If you are expecting an integer, draw it to an integer. The same goes for float, boolean, etc.
These PHP functions can be useful though: www.php.net/strip_tags www.php.net/ctype_alpha
source to share
Also, if you have a known set of valid URLs, it is a good idea to whitelist Allowed URLs. You could even do it dynamically, having a DB table containing the allowed URLs - pull this from the database, compare against the passed URL parameter. Alternatively, you can use whitelisting (say you are allowed to transfer domains, but the rest of the url changes ... you can change the domain whitelist and / or use regex to determine validity).
At the very least, make sure you use strip_tags or the built-in mysql escape sequences (if using PHP5, parameterizing your SQL queries solves these problems).
source to share
It would be more like cake to use the Sanitize class . In this case, Sanitize :: escape () or Sanitize :: paranoid () seems appropriate.
source to share