Recover/Decode encoded php code - php

we had an ex employee handling our servers and he left due to some issues. now he encoded all the php files on the server and we are struggling to get it back.
can any one help in decoding the file or maybe let us know which encryption is it and how to recover codes.
We tried using many online decoders and other stack over flow suggested techniques but ended up with a buggy code.
I have pasted a sample code on https://pastebin.com/4uwZLZVF
A sample first line
<?php {"G\x4cOB\x41L\x53"}["gb\x73\x73\x69\x62"]="t\x65\x63hid";${"\x47\x4c\x4f\x42\x41\x4c\x53"}["\x66\x65ll\x77\x68j\x6c"]="co\x6et\x5f\x72e\x73\x32";

You could start by decoding the \xNN escape sequences in the string literals, which should at least give you some idea of what the code is doing. For example, the first line becomes:
<?php {"GLOBALS"}["gbssib"]="techid";${"GLOBALS"}["fellwhjl"]="cont_res2";
(And no, I have no idea why the first {"GLOBALS"} has no $ before it. Looks like a syntax error to me.)
Anyway, if the ex-employee didn't originally write that code, you'd probably be best off restoring it from backups. (You do have backups, right?) Treat anything they did write as untrustworthy —given that they were willing to sabotage their employer to this extent, who knows what kind of other traps they may have buried in the code. Even if you manage to deobfuscate it, unless you're willing to carefully inspect every line of the code (which probably takes as much work as just reimplementing it) you can't be sure it doesn't contain some malware that compromises your server.
Oh, and call your lawyer. Given this kind of deliberate sabotage, there's got to be something you can sue your ex-employee for — probably breach of contract, at least. Assuming you can still track them down, that is. But you might, since they presumably had some motive for doing this to you (e.g. to extort extra money from you for the unobfuscated code), and unless it's pure revenge, they can't get what they want if they just walk away without any trace.
(Of course, that's assuming you didn't breach the contract you had with them first. If the reason they left you with obfuscated code is because you promised to pay them and didn't, then you probably won't have much luck with suing them, and should either pay up or give up. Consulting a lawyer might still be worthwhile, if you're not sure if you're in the right or not. If you do decide to pay the ex-employee for the unobfuscated code, you might still want to treat it as suspect — although, if it turns out that it still doesn't do what you want after you've fully paid for it, you're at least in a much stronger position legally. Oh, and if you didn't have a written contract before, make sure to insist on one now before paying anything. And have your lawyer read it before you sign it.)

Related

Regex for a malware scanner (PHP)

Good day all! Today's problem is simple.
We have many sites on shared servers and sometimes they get hacked by malware, they start to send email or they try to infect the rest of the neighborhood sites.
After a while spending time to clean up the files on many servers I started to think that maybe having a script that takes a look at the php files could be a really help for me.
Having a full antivirus for each website is a bit "too much" what I like to have is something I can manage remotely, and that will give me some clues on the scanned webserver.
So I thought about a simple PHP script, it simply scans every directory and every file in search of suspicious patterns. I actually use these two regex:
/eval\((base64|eval|\$_|\$\$|\$[A-Za-z_0-9\{]*(\(|\{|\[))/i
/mail\(/i
I know, the second one is very naive, but it makes the job, because I want to know if there is a mail call on some php file.
I have tried to use the token_get_all but the only useful token I found was the T_EVAL one, so I returned to the regex way.
My problem actually is that these two regex are:
un-optimized (I'm feeling regex is a bit to much cpu/time consuming)
far away to be precise
What I'm asking is:
got some better idea for achieving the same result?
I would like to match also these patterns:
ev​al(gzinflate(base​64_de​code('...');
ev​al(gzuncompress(base​64_de​code('...');
ev​al(gzinflate(str_rot13(base​64_de​code('...');
I feel that eval|base64|gzinflate|gzuncompress|gzinflate should be the "initial" patterns to search for, but modifing the regexp into:
/eval\((base64|eval|gzinflate|gzuncompress|gzinflate\$_|\$\$|\$[A-Za-z_0-9\{]*(\(|\{|\[))/i
doesn't give me the results I espected.
Well, of course if you have better ideas, will be all more than welcome.
NOTE
I understand that the question is very broad, but I would like to have ideas on this topic since it is something very time consuming having to handle hundreds of websites without any kind of protection.
If this isn't the right place to post this question, I'll delete it, I don't want to sully the board.
ANOTHER NOTE
This isn't "the solution" I only want a structured tool to start with in case of problems, something I can use easily from home (or with a CRON), that just warn me about something odd, there will be a tons of false positive indeed.
My first thought is professional virus scan and malware removal software. If you want to try to do this yourself, you might consider making a database of md5() digests of your PHP scripts. Scan the directories, make the digests, store them in a database. On a re-scan, compare the digests. If there are any new digests (new PHP files appeared) or missing digests (PHP files went away) or changed digests (PHP files were modified) it would give you a quick heads-up that something was different, and you could investigate if the change was unexpected.
Once your server get hacked, there is no way to clean it.
The only safe way to proceed once an infection is detected is to build a new server and import the data into it (after a check of these data)
If the server is infected you can't trust it anymore because he can lie to you about anything, like the content of files.
I know it sounds painful, but there is no hope to fully recover from an infection and be sure you have recover from it.

Devil-Shell code injected into my site

I am looking for some advice - I hope someone can help
My php site got hacked and I just found this code 'Script Encoded by Devil-Shell':
eval(gzinflate(base64_decode($encoded)))
And all these random letters/numbers...
I have a few questions:
What will happen if I delete this code? Will it have a knock on effect?
Is my site ruined?
Is there anything that can be done?
Thanks for your help.
It pretty much looks like a backdoor - I'd suggest to comment this out.
As long as $encoded is a variable that can be set externally (through HTTP GET or POST for example), anyone can execute any code on your server.
Unzip it to see what it does. Ensure it cannot be executed. Understand the damage it has done
Find your flaw in security
If that is PHP code, that is pretty serious, as they were able to append to a PHP file or to add their PHP malicious file. They basically own the server. Apart from general advices (fix your security, that can be a year of work :)) some real-life tips:
Don't erase logs, application logs or web server or db logs; keep them, it is very unlikely someone injected anything bad (apart from strings) there. Collect and keep all the logs, trust me they will be useful in the future if something bad happens.
They could have compromised the whole server with an attack like that. You need to be careful with your hosting company: they could consider you responsible for data breaches in other people's data, config, etc... It depends on their configuration and the agreement you signed with them.
Do not consider anything safe: the DB could be compromised as well, all keys and passwords and passphrases and sessionIDs you have stored since now are insecure and are in the hands of them now. So replace them ALL, as their aim could be not you but your user, and they are totally in control of their browsers too now (if they want).
You can comment that out, it seems safe enough; but they will add it again, in more subtle forms. Consider that.
Check (if you can) the traffic FROM your website. Usually they build simple webshells like that to be part of a bigger botnet. Usually they are used for Distribuited Denial of Service (DDOS), bitcoin mining or traffic exchange. So you could be considered legally responsible for such attacks/illegal behaviours as they are connected to your account and it is yours the contract for hosting.
In the internet this topic is called 'Intrustion Response' or 'Attack Response'. It is usually tailored only for big enterprises so I doubt you can find anything useful, but at least for theoretical topics it may help to google for it http://www.certiguide.com/secplus/cg_sp_SixStepIncidentResponseProcess.htm

Code obfuscation and runtime behaviour changes

Is there any way that you may create a puzzle of three pieces with your code that you allows you to have an encrypted string, a function built specifically for that string and only for that one, (string that in its decrypted form is actually code/instructions to execute). And the third and most important, the final piece would be the context that makes the execution of function possible, and that environment state must be unforgeable. So the function to be executed on the matching string only one time, only one environment state, and after that to expire. It must be as a perfect clock mechanism that even only one piece that is missing to make it "un...tickable" (unable to tick, as in "to function", of course, because every part is vital).
I am speaking about script languages here, where exists something like eval, but it can be applied as a general technique.
Using some kind of "domino" effect based of all kinds of memory states, and variables, random, or not, you could create something similar to a "leak effect" letting bits of your code in a structured (but hidden) place, so that at the end, using a strange tool as a "code funnel" all to arrange in an execution flow.
As I do not know of anything like this, my words are made-ups in order to be able to give then any kind of readable and understandable form.
My question is exactly about this... is it possible? Is there any help I can get? As any ideas somewhere? Because I cannot find anything right now that can hold such an effect.
And of course you might find no reason for me to ask for such a thing, as you could say that no one is interested in my code, or I suffer of paranoia. But still consider it might be a reason out there. No, it surely is a reason for me wanting to know this.
And please don't hush and jump to conclusions like "it was specified clearly that this is not a discussion forum", as this is a problem I am facing with some urgent need for a solution. And as I have few experience about a lot of things, including serious math, and a solid algorithmic thinking, I am in a cry for help. So I thank those who will give any consideration to this matter.
This is essentially impossible, at a very fundamental level.
You want to give someone some information (your code). You want them to be able to execute the code once, in one particular state (that you don't define very well). But you don't want them to be able to inspect that code, or execute it under other circumstances. Impossible.
A program on that person's machine (that will execute the code) must be able to inspect the code, in order to be able to execute it. So other programs on that machine will also be able to inspect the code.
You can encrypt your code, so that arbitrary programs can't inspect it, and you regain control. But the program intended to execute the code still needs to inspect it, so you'll have to somehow get the information it needs to decrypt the code.
But now you're right back to your original problem: You some information (the decryption key), which you want to give the user for one particular use (decrypting and running your code under only the circumstances you specify), and not for any others.
More interestingly, you could instead encrypt your code with a hash value derived from the parts of the environment you want to check (how exactly you derive the key is impossible to say without knowing what you want to check). Then, if the user (or a program executing your code on their behalf) wants to inspect the code, it will have to follow the same process of deriving a hash value from the environment and have the correct environment. But the user could arrange to collect the hash value from that environment and keep it, allowing them to inspect your code whenever they want.
Plus, I have no idea what you could possibly check that actually guarantees the correct environment. If the program is supposed to check that it is correctly running itself (with no modifications to spy on your code) before decrypting the secret part of itself and running that, then a spy can easily pull out the encrypted stuff, worked out from the (unencrypted) checking code what computations are done to check the environment, and then do their own calculations based on the "correct" environment rather than the one that actually exists.
All you can do, in the end, is make the process of recovering your top secret code more annoying, so that it de-motivates from bothering. Most people will never bother to look at your code anyway; they just don't care. Most of the remaining ones will give up at the slightest resistance (though it may put them off using your software). The ones who are still trying after that... there's always a chance (if your secret code is really that valuable/interesting) that there will be sufficiently motivated people who will get around whatever you do (unless you just never give anyone your code in the first place). So my inclination is to just put some small easy effort into obscuring your secret code, and don't worry about achieving perfect security, because it's impossible.
You could simply encrypt the code using a symmetric encryption. Encrypt it using a random key, store that key on the computer, and then include in the encrypted code a part that deletes that key from memory when the code is run. Of course it would be relatively easy for someone to copy the key before it was deleted and restore it to memory later, but you could put it somewhere obscure, and I think no matter what you do someone could restore the computer to an earlier state (using backup software).
#Ben, interesting presentation, I believe that I was thinking about this from the very moment I understood what can be done, and what cannot be done. I thought of every possible situation you mention, and even more, indeed it seems there is no way. Maybe I should limit myself at just making it as much as a headache as I can. Not only that is a super-secret code, as you named it, but I have another intention in hiding it, it's that, pardon my lack of modesty, it really is an interesting code, and I really want to filter those to see it, if it takes a genius to make it from A to C without going through B, and it must take another to figure out how. I though it was my lack of experience that kept me down with is unsolvable problem. But still, I am always put in front of such seeming impossible situations, and I usually raise hell to find the solution, I manage it just fine. But now it just that I cannot surrender.
I might just have known the answer since the beginning, that no matter how much you try it can't be done, and of course it is easy to find out why, because it is not normal, or correct, it must depend on your knowledge and experience the limit of what you are creating. And with that in mind it is obviously why there must be a way someone better, and surely there will be someone better, than you to overcome you. Even if this is, for my at least, subjectively speaking, such troublesome. Well then, I guess I'll give my best to lessen those to know my super-secret code. After all even god is great puzzle maker.
Anyway I highly appreciate your answer.
P.S. Sorry for the late answer, but as I could not answer my question for 8 hours, I had to wait, and after that I couldn't be able to find any avaible time to do it.

Releasing commerical PHP code. Do you obfuscate or compile it? Or just deliver as-is?

Possible reasons:
1) so the user can't figure out the code and "issue himself more licenses" or other stuff that is commercially sensitive to you
2) so the user can't "just make a tiny change" and break what he doesn't understand, then tell you he didn't change anything and expect you to fix it (sure, you can make him pay, but it's easier to avoid the hassle in the first place)
3) so the customer can't take some of your software and use it do develop new products
4) you are embarrassed to let your uncommented spaghetti code be seen ;-)
5) any more?
What do you generally do? And how do you do it?
If hosting the php code on your servers is not an option, the best thing is to simply deliver the source code with a restrictive license and accept the risks you outlined above. If the user "issues more licenses" and it violates your terms, you can pursue legal actions.
On the receiving end, I have purchased PHP software that was ofsucated/encoded with ionCube PHP Encoder (http://www.ioncube.com/). It required adding an additional server component and including effectively closed-source code no our servers, neither of which our IT team was happy about. But it prevented us from fiddling with the source as you are attempting.
I deliver it as is. End-users expect to be able to edit the code whether it's free or commercial. Most of them aren't pirates, so getting in their way will just hurt your business (less happy customers = less positive mentions and referrals). The pirates will steal your software whether you obfuscate/encode it or not, anyway.
If a client breaks my code and try to pin it on me I offer to restore the code to the last known working configuration. This usually ends the conversation because they know it was a modification they made.
Seems like an unnecessary precaution to me. Even if you obfuscate it it can still be redistributed. As a developer, piracy is a known risk and the best way to avoid it is to release software that is open source. :)
I would seriously think twice about doing business with a developer in the future if I purchased a script that was obfuscated (making it difficult for me to make changes). I mean.. what PHP script needs ZERO modification to get it to do exactly what you want it to?
Concerning point #2:
You can always generate a hash of your deliverables. Very simple method: generate an md5 hash using the source files as input. If you suspect tampering when receiving a support call, simply hash the deployed files to figure out if your client has tampered with the code and tries to get you to fix their mess.
This is non-intrusive (you just hash before you deliver, and keep the hashes in your files) and a quite safe way to check the contents of your files.
No one has addressed that delivering the licensing source allows customers to switch it off and have unlimited licences. That is my main concern

What is your experience of PHP encrypters? Which one would you recommend?

We have an application that is written in PHP that we are going to license to a customer. Our company believes that the customer might intend to steal the source code and create their own fork of the software, therefore we want to encrypt the source code.
I have searched some for PHP-encrypters and found several that seems good, but since we have no previous experience of PHP-encrypters it hard to say which one is the best. Which PHP encrypters have you used and what is your experience?
So, First:
It is impossible to encrypt your entire code base because at some point there has to be an eval statement, and if the user changes the eval to an echo, they get all of your code in the browser.
And here is a bunch of people who agree with me.
Furthermore:
People will offer you obfuscators, but no amount of obfuscation can prevent someone from getting at your code. None. If your computer can run it, or in the case of movies and music if it can play it, the user can get at it. Even compiling it to machine code just makes the job a little more difficult. If you use an obfuscator, you are just fooling yourself. Worse, you're also disallowing your users from fixing bugs or making modifications. - Schwern
Now thats done:
Bytecompiling is something completely different than encrypting. It makes the PHP code into already interpreted bytes, similar to an exe file. You can include these files just like any other php file.
The byte code produced is able to be reverse engineered, but it would take lots of time and is not worth the company's time.
Check out the byte compiler PHP extension.
I'd also like to note that PHP comes with several ways of reverse engineering classes. Such as the Reflection Class. This basically allows people to see every method, variables, and constant in each of your classes without the need for your source code.
Frankly, once someone sees the functions you use, it is pretty easy to piece it together after that.
There's a lot of obfusticaters out there masquerading as encrypters.
If you really must encrypt your code use Zend.
IMHO shutting your customers out of your code is inherently evil and would rather hide some symbology in the code and sell it under a no-modify/re-sell contract. Then sue the ass off them if they try to sell it on. You could argue that encrypting your code closes down a business opportunity ;) !
C.

Categories