Joomla: correct way to sanitize file data - php

I am writing import script from csv files and I need to validate data, most of the data is strings so I want to use something like Jinput to sanitize it.
Is there is something Joomla already have for this purpose?
It would be ideal to have something like
$field = JSanitizer::get($data/*array with data*/, "fieldname"/*name of field*/,
'string'/*type of data*/, 'null'/*default value*/);
Also I would need it to work both in Joomla 2.5 and 3.0 versions.

You are probably looking for JFilterInput::clean() This would work as follows:
$field = JFilterInput::clean($data[$fieldname], 'filter');
This does not give a way to set a default value, so you would have to handle that afterwards. This should be the same filtering that is typically done with JInput as well as on JForm elements if you write custom components.
I can't seem to find a good list of all the filters, but you can see an old version of the source here: http://docs.joomla.org/API16:JFilterInput/clean. Most recent version of the function starts at line 162 here: https://github.com/joomla/joomla-cms/blob/master/libraries/joomla/filter/input.php
Note also that you want to pull the field out of the data array yourself. You can actually send it the entire array without a filter setting and it should at least check the entire array for XSS and other issues. If you want more nuanced filtering for integers and such, it would best to do it field by field.

$field = JFilterInput::clean($data[$fieldname], 'filter');
will fire a notice
"Non-static method JFilterInput::clean() should not be called statically"
You should initiate this with JFilterInput::getInstance() first and call it dynamically e.g.:
$field = JFilterInput::getInstance()->clean($data[$fieldname], 'filter');
Tom

You should read Joomla docs and use something like this before parsing file : $string = JRequest::getString( 'description' );
This should work across all version since 1.5
There has been some github projects to implement html purifier as plugin, i found this, but havent chance to tested it, but it should work though.

Related

How to make dynamic links in php without eval()

I am using wordpress for a web site. I am using snippets (my own custom php code) to fetch data from a database and echo that data onto my web site.
if($_GET['commentID'] && is_numeric($_GET['commentID'])){
$comment_id=$_GET['commentID'];
$sql="SELECT comments FROM database WHERE commentID=$comment_id";
$result=$database->get_results($sql);
echo "<dl><dt>Comments:</dt>";
foreach($result as $item):
echo "<dd>".$item->comment."</dd>";
endforeach;
echo "</dl>";
}
This specific page reads an ID from the URL and shows all comments related to that ID. In most cases, these comments are texts. But some comments should be able to point to other pages on my web site.
For example, I would like to be able to input into the comment-field in the database:
This is a magnificent comment. You should also check out this other section for more information
where getURLtoSectionPage() is a function I have declared in my functions.php to provide the static URLs to each section of my home page in order to prevent broken links if I change my URL pattern in the future.
I do not want to do this by using eval(), and I have not been able to accomplish this by using output buffers either. I would be grateful for any hints as to how I can get this working as safely and cleanly as possible. I do not wish to execute any custom php code, only make function calls to my already existing functions which validates input parameters.
Update:
Thanks for your replies. I have been thinking of this problem a lot, and spent the evening experimenting, and I have come up with the following solution.
My SQL "shortcode":
This is a magnificent comment. You should also check out this other section for more information
My php snippet in wordpress:
ob_start();
// All my code that echo content to my page comes here
// Retrieve ID from url
// Echo all page contents
// Finished generating page contents
$entire_page=ob_get_clean();
replaceInternalLinks($entire_page);
PHP function in my functions.php in wordpress
if(!function_exists("replaceInternalLinks")){
function replaceInternalLinks($reference){
mb_ereg_search_init($reference,"\[custom_func:([^\]]*):([^\]]*)\]");
if(mb_ereg_search()){
$matches = mb_ereg_search_getregs(); //get first result
do{
if($matches[1]=="getURLtoSectionPage" && is_numeric($matches[2])){
$reference=str_replace($matches[0],getURLtoSectionPage($matches[2]),$reference);
}else{
echo "Help! An unvalid function has been inserted into my tables. Have I been hacked?";
}
$matches = mb_ereg_search_regs();//get next result
}while($matches);
}
echo $reference;
}
}
This way I can decide which functions it is possible to call via the shortcode format and can validate that only integer references can be used.
I am safe now?
Don't store the code in the database, store the ID, then process it when you need to. BTW, I'm assuming you really need it to be dynamic, and you can't just store the final URL.
So, I'd change your example comment-field text to something like:
This is a magnificent comment. You should also check out this other section for more information
Then, when you need to display that text, do something like a regular expression search-replace on 'href="#comment-([0-9]+)"', calling your getURLtoSectionPage() function at that point.
Does that make sense?
I do not want to do this by using eval(), and I have not been able to accomplish this by using output buffers either. I would be grateful for any hints as to how I can get this working as safely and cleanly as possible. I do not wish to execute any custom php code, only make function calls to my already existing functions which validates input parameters.
Eval is a terrible approach, as is allowing people to submit raw PHP at all. It's highly error-prone and the results of an error could be catastrophic (and that's without even considering the possibly that code designed by a malicious attacker gets submitted).
You need to use something custom. Possibly something inspired by BBCode.

PHP - how to find the meta information of an internal/built-in method programmatically?

Is it possible to find the data about a built in method in PHP via code?
For example, we have array_key_exists() which is an internal method.
I want to find out the parameters in this function programatically. The reason is, there is an up coming interview, and I will have to write code on Notepad. There will not be any internet connection to see PHP documentation.
If I can get the information about built in methods via code, it will be really helpful.
Is it at all possible to print meta data of a function? I am not asking about user defined functions, but about PHP's built in functions.
Thanks a lot.
You are looking for Reflection i think:
$refFunc = new ReflectionFunction('preg_replace');
foreach( $refFunc->getParameters() as $param ){
print $param;
}
http://php.net/manual/de/class.reflectionfunction.php

Add php function to all POSTs and REQUESTs variables

I have a very old client who is now having issues with security because of the MYSQL Injection. This client does not have enough money to change his PHP database functions to PDO or MYSQLI. Nevertheless, he suggested that he wants a function that prevents mysql injuction. He is fully aware that the function is not perfect. But, he does not have any other temporary way right now. the function that I wrote for him is called safe();. Here comes my question. How can I apply the function to all POSTs and REQUESTs in his site. His site has many files, it will take hours to change. is there anything that I can add in the Header of every file that applies my function to all POSTs and REQUESTs variables?
something that maybe looks like this :
$_POST[*] = safe($_POST[*]);
Of course, the above code does not work. but I hope you get the idea.
You can use array_map, but I doubt it'll be perfect solution:
$final = array_map( "mysql_real_escape_string", $_POST );
In the end $_POST and $_GET are just arrays.
You could do a foreach like
foreach ($_POST as $key => $value) {
safe($value);
}
if they have old php servers etc. So if you have a general file that is included over the whole website and the "normal" functions aren't an option, this could be the back-up plan.
You are describing the infamous Magic Quotes, which are still available if the server is older than PHP/5.4.0 (which I presume is the case).
Please note that they affect all POST data, including that which is not going to be injected in a SQL query.
If you prefer your safe() function, you can simply write a simple script that makes the change and call it via auto_prepend_file.
Possible duplicate of https://stackoverflow.com/questions/15664021/php-escaping-vars-posted-through-var-and-got-by-postvari-with-a-meth
As I was told, there's no universal method, but you can give it a try through foreaching the $_POST array

How to use Request::factory()->execute() to call an script from another library in the same host

I'm using Kohana 3.2, and I want to be able to call another script (unrelated to Kohana, outside of its 'jurisdiction') that returns a application/json response.
When I tried using:
$response = json_decode(Request::factory('/scripts/index.php?id=json')->execute()->body());
It errors out saying there's no route to scripts/index.php. So I tried using Request_Client_External
Request_Client_External::factory()->execute(Request::factory('/scripts/index.php?page=s'))->body();
Gives me Request_Exception [ 0 ]: Error fetching remote /scripts/index.php?page=s [ status 0 ] Could not resolve host: scripts; Host not found. It appears it need a full flagged URL using http/https, but how to avoid the overhead of it doing a real external request?
Doing a
Request::factory(url::site('/scripts/index.php?page=s', 'http'))->execute()
works but is it considered "external"?
The short answer to your question is that the only way to use Request::factory()->execute() to achieve that is to use pass it the full url (with whatever "overhead" that entails, which shouldn't be too much: your server's probably quite good at talking to itself).
Otherwise, ideally you'd put the functionality of scripts into a library and call that from Kohana. However it sounds like that's not an option for you. If you have to leave /scripts/index.php untouched and insist on an 'internal' request, you could use PHP's output buffering, as illustrated below. But there are a bunch of caveats so I wouldn't recommend it: the best way is passing a full url.
// Go one level deeper into output buffering
ob_start();
// Mimic your query string ?id=json (see first caveat below)
$_GET = $_REQUEST = array('id' => 'json');
// Get rid of $_POST and $_FILES
$_POST = $_FILES = array();
// Read the file's contents as $json
include('/scripts/index.php');
$json = ob_get_clean();
$response = json_decode($json);
Some caveats.
Firstly, the code changes $_GLOBALS. You probably don't use these in your Kohana code (you use $this->request->get() like a good HMVCer, right?). But in case you do, you should 'remember' and then restore the values, putting $old_globals = $GLOBALS; etc. before the above code, and $GLOBALS = $old_globals; after.
Sessions: if your /scripts/index.php uses `session_start() this will cause a warning if you've already started a session at this point in Kohana.
Note that all variables set in scripts/index.php will remain set in the context you're in. If you want to avoid possible conflicts with that context, you'd start a new context, i.e. wrap the above into its own function.
Finally, you'd also need to make sure that /scripts/index.php doesn't do anything like Kohana::base_url = 'something_else', or touch any other static attributes, or do something catastrophic using this.

Formatting the POST array to an SQL insert\update string in codeigniter 2

I'm trying to automate form creation and submission in codeigniter.
Basically what I want is to find a way to go over all the data in the POST array and format it correctly to an insert or update sql query.
The problem is I don't know how to access to whole POST array in CI, all I know of is the $this->input->post(field_name) way which only gives you a specific field.
Ideally I would want to send the POST array to the $this->db->insert_string() or $this->db->update_string() to do the job for me.
I know I can still use the php native $_POST array, but this is not recommended and not as secure as CI's input class.
Anyone know a way to do this?
Thanks,
Amos
Eventually I found out that the input class cleans the $_POST array automatically (not talking about XSS cleaning) and so the only advantage to use $this->input->post(something) is that it checks if that key exists.
Since I need the whole array I don't need that check and can safely use $this->db->insert_string($_POST).
If I you do want XSS cleaning you can either turn it on globally in the config or use geocine's answer (I would go for a mix of the 2 examples he gave).
Another way to go if you want the whole array with XSS cleaning and without it turned on globally is to go with WanWizard's Input library extension found here: http://codeigniter.com/forums/viewthread/172705/#821150
foreach($_POST as $key => $value) {
$value = $this->input->post($key);
//do something
}
or
$keys = array_keys($_POST);
for($i=0,$max=count($keys);$i<=$max;$i++)
{
$value = $this->input->xss_clean($_POST[$keys[$i]]);
//do something
}

Categories