Malicious code is code that interferes with the normal operation of a website. It can be embedded in themes, databases, files and plugins.


More videos on our channel - learn internet marketing with SEMANTICA

The result of the work of malicious code can be the removal of some useful content, or its publication on a third-party resource. In this way, cybercriminals can organize theft of content. It is especially offensive if a young resource with copyright articles has been exposed to this. One might get the impression that it was he who stole the content from an older resource.

Also, malicious code can place hidden links to third-party pages available for search engines in a free theme. These links will not always be harmful, but the weight of the main site is guaranteed to suffer.

The general purpose of all malicious codes is to disrupt web pages.

Outwardly, the malicious code is a chaotic set of characters. In reality, this nonsense hides an encrypted code containing a sequence of commands.

How malicious code gets to the site

There are two ways in which malicious code can enter a website.

1. Downloading files and plugins from questionable and unreliable resources. Most often, encrypted links penetrate the site in this way. Explicit code rarely enters a site this way.

2. followed by penetration. This method is considered more dangerous, because hacking a web page makes it possible to transfer not only "one-time" code, but also entire constructs with elements of a malicious program (malware).

Such code is very difficult to destroy, since it can recover after being deleted.

Checking the site for malicious code

Keep in mind that these insidious constructs can appear not only in the active topic, but also in any resource file. There are several ways to find them:

  • Manually. To do this, you need to compare the contents of all current files with uninfected versions of the backup. Anything different needs to be removed.
  • Using security plugins. In particular, WordPress offers the Wordfence Security plugin. It has the option to scan page files for extraneous code content.
  • With the help of a hosting support. The site owner has the right to contact them with a request to scan the resource with their antivirus. As a result, they will provide a report showing the presence of infected files. These files can be cleaned of extraneous structures using a regular text editor.
  • Through SSH access to the site. The search itself is carried out using the commands:

find / current page directory -type f -iname "*" -exek - "eval" () \; > ./eval.log

find / current page directory -type f -iname "*" -exek- "base64" () \; > ./base64.log

find / current page directory -type f -iname "*" -exek - "file_get_contents" () \; > ./file_get_contents.log

As a result of their execution, information about suspicious files will be obtained. The list of these files will be written to the log stored in the current directory.

  • Checking a site for malicious code using the eval function. This php function launches any, even encrypted code for execution. As one of the arguments, the type of encoding is supplied to the input of this function (as a rule, it is base64_decode or str_rot13). It is thanks to the use of popular encodings that the malicious code looks like a meaningless set of Latin characters.

Open the page editor.

Copy the contents of the functions.php file to the clipboard.

Paste it into any text editor (notepad).

Find the eval command.

  • Before removing the malicious code, analyze what parameters the function expects to enter. Because parameters come in encrypted form, they need to be decrypted using decoders. Having recognized the input parameter, you can decide on its further location in the text of the functions.php file.

Removing malicious code

After detecting malicious code, it simply needs to be removed as a regular line in a text file.

Protection against malicious code

In order to prevent the appearance of malicious code on the site, a number of preventive measures must be followed.

Use only proven software:

  • Only download distributions from trusted sources.
  • Run the server software update at the same time.
  • Perform regular server security audits.
  • Remove obsolete debug scripts.

Install strong passwords on the server software:

  • Come up with a 12-character construction that includes numbers and letters in different cases.
  • For each of the services, create your own unique password.
  • Change your passwords every 3 months.

Control the data entered by users:

  • Set up HTML markup filters in the input fields, the content of which will be included in the page code.
  • Organize a server-side validation of the input data against the valid interval.
  • Use WAF. Web Application Firewall is a powerful tool to protect your site from hacker attacks.

Differentiate access rights to your resource.

Block or restrict access to the administration tools of your site's engine and its databases. Also, close access to configuration files and working code backups.

The sites that have the ability to download user files are most susceptible to such penetration of malicious code.

1. Organize protection from bots. For these purposes, many CMS are equipped with special plugins;

2. Configure validation of user-entered data:

  • Prevent JavaScript code from being inserted inside the t> construct.
  • Maintain a list of safe HTML tags and filter out constructs not on this list.
  • Analyze the links that users send.
  • There are special services for this, for example the Safe Browsing API. It allows you to check the security of a document by URL.

How to prevent accidental placement of malicious code.

  • Monitor the software you are using carefully:

Download CMS libraries and extensions only from trusted sources, and best of all from official sites.

Study the code of non-standard extensions that you are going to put on the engine of your site.

  • Place your ads very carefully:

Publish on your site ads that only reliable advertisers offer.

Try to post static content on your page.

Beware of hidden block affiliate programs.

This problem may be caused by a malicious program injected into the browser. This type of malware aims to change browser settings. Any of the following situations may occur:

If you see a pop-up window with a link to a third-party support website, or you are sure you have been the target of fraudulent activity, please see this article.

Performing a scan Norton Power Eraser - Scan for unwanted applications

    Select Desktop as the location and click Save.

    Double-click NPE.exe to start Norton Power Eraser.

    If a window appears

    Scan for unwanted applications.

    The scan results of Norton Power Eraser will be displayed in a window.

    In the window Scanning for unwanted applications completed click the Uninstall button next to the unwanted application or toolbar.

    Follow the instructions on the screen.

    After the uninstallation process is complete, restart your computer.

If Norton Power Eraser fails to remove unwanted toolbars, manually remove them using Add or Remove Programs or Remove a Program from the toolbar. Ad serving programs typically install new toolbars in browsers and change the default search engine. To completely remove unwanted toolbars and search services, you need to reset your web browser settings.

    Run Internet Explorer.

    From the Tools menu, select Add-on management.

    In the Add-ins window, select Toolbars and extensions For more information, see Types of add-ins.

    If the displayed list contains a suspicious toolbar, select it and click the Disable button.

    In the Add-ins window, select Search providers For more information, see Types of add-ins.

    Select a search service and click Use as default.

    Select an unknown search provider and click Remove and Close.

    From the Tools menu, select Internet options.

    On the General tab under Homepage enter the address of your preferred homepage.

    Click the Apply and OK buttons.

    On the desktop, right-click the Internet Explorer icon and select Properties.

    In the window Internet Explorer Properties on the Shortcut tab, delete the text after iexplore.exe in the Target field.

    Click Apply and OK to save the changes.

    Click the Close button.

    Run Google chrome.

    In the upper right corner, click the icon Setting up and managing Google Chrome, then select Settings.

    In the Chrome area, click Extensions.

    In the Extensions window, select unknown extensions and click the trash can icon.

    In the Chrome area, click Settings.

    In the Settings window, select Following pages In chapter Initial group.

    In the window Start Pages select suspicious entries and click the X icon.

    Click OK.

    In the Settings window, select Show home button In chapter Appearance and click Change.

    In the window Home page select item Quick access page and click OK.

    In the Settings window, click in the Search section.

    In the window Search engines select your preferred search engine and click Use as default.

    In the list Default search settings select an unknown search service and click the X icon.

    Click the Finish button.

    Start Firefox.

    In the upper right corner, click the Open Menu icon and select Add-ons.

    On the page Add-on management select Extensions.

    Check the list of extensions for suspicious entries. If they are, select the extension and click Disable.

    Click the Open Menu icon and select Settings.

    On the Main tab of the Settings window, click Restore to default.

    Click OK.

    In the Firefox window, click the down arrow icon next to the URL field and select Search engine management.

    In the window List management search engines select an unknown search provider and click the Remove button.

    Click OK.

Scan Norton Power Eraser

    Double-click NPE.exe to start Norton Power Eraser.

    If a window appears User account management, click Yes or Continue.

    Review the terms of the license agreement and click Accept.

    In the Norton Power Eraser window, click the icon Scan for threats.

    By default, Norton Power Eraser scans your system for rootkits and prompts you to restart your system. When prompted to restart the system, click the Restart button. To refuse scanning for rootkits, select.

    After restarting the computer, the scanning process starts automatically. Follow the instructions on the screen.

    Wait for the scan results.

Video clip

Need more help?

Check for incorrect DNS settings

    control

    Click the Network and Internet icon, and then click Network and Sharing Center. In the left pane, click Change adapter settings.

    On Windows XP: Double-click the Network Connections icon.

    Right-click the network adapter that is currently active, and then click Properties.

    If the User Account Control prompt appears, click Yes or Continue.

    In the Network Connection Properties window, under "This connection uses the following items", click Internet Protocol (TCP / IP) or Internet Protocol Version 4 (TCP / IPv4).

    Click Properties.

    In the Internet Protocol (TCP / IP) Properties window, on the General tab, check the DNS server settings.

    • If Use the following DNS server addresses radio button is selected, check the server addresses. Make sure that the DNS server addresses displayed are the same that are provided to you by your Internet service provider or your network administrator.

      If the DNS server address starts with 85.255.11x.x, then it is more likely that the DNS cache has been poisoned as the result of a Pharming attack.

Fix incorrect Windows host file settings

    Press the Windows + R keys to open the Run dialog box.

    Type in the following text, and then press Enter.

    C: \ Windows \ System32 \ Drivers \ etc

    Replace the drive letter if C: drive is not the system drive.

    For each Hosts file that you find, right-click the file, and then click Open With or Open.

    Double-click Notepad from the list of programs.

    Remove any line that appears in your hosts file without an # at the beginning, apart from the "127.0.0.1 localhost" line.

    On the File menu, select Save.

    Check if you can access the Internet.

Fix incorrect proxy settings

    If you have not configured your computer to use proxy for the Internet connection, you can skip this Step.

    Start Internet Explorer.

    On the Tools menu, select Internet Options.

    On the Connections tab, click LAN Settings.

    Verify that your proxy settings are correct. Do one of the following:

    If the proxy settings are incorrect, make sure that you enter the correct proxy settings.

    If the proxy settings are correct, temporarily disable the proxy. Uncheck Use a proxy server for your LAN.

    In the Internet Options window, click Apply> OK.

Uninstall or disable unknown toolbars

    If you want to completely remove a toolbar, you can use Add / Remove Programs or Uninstall a Program in the Control Panel.

    Start Internet Explorer.

    On the Tools menu, click Manage Add-ons.

    If you find any unknown toolbar that is listed, select the toolbar, and then click Disable.

    Click Close.

    If the issue persists, go to Step 5.

Run a scan using Norton Power Eraser

    Save the file to Windows desktop.

    Open the windows run dialog (Windows key + R).

    Drag and drop NPE.exe into the run box, this will automatically populate it with the full path Add the following switch to the end of the line:

    The run line should look like:

    "C: \ Documents and Settings \ user_name \ Desktop \ NPE.exe" / VSS 111

    Click OK.

  1. If the scan comes clean, go to Step 6.

Is short for "Malicious Software". It is a term generally used for software installed on your computer that is designed to infiltrate or damage a computer system without the owner "s informed consent. Sometimes a problem with Firefox may be a result of malware installed on your computer, that you may not be aware of. This article describes what common symptoms are and how to prevent malware from being installed and get rid of them.

Table of Contents

How do I know that my Firefox problem is a result of malware?

Symptoms are various and depend on the malware but if you have one or several of these behaviors, you may have malware installed on your computer.

  • Some ad popups display all the time, although you "ve blocked popups. For more information on blocking popups, see.
  • Your searches are redirected to another site in order to feed you content from that website and you are being disallowed from blocking them. For more information, see What to do when searches take you to the wrong search website.
  • Your home page has been hijacked... For more information on setting your home page, see How to set the home page.
  • Firefox never finishes loading or can "t load certain websites... For more information, see Websites show a spinning wheel and never finish loading and Firefox cannot load certain websites.
  • Firefox crashes or hangs a lot. For more information, see Firefox crashes - Troubleshoot, prevent and get help fixing crashes and Firefox hangs or is not responding - How to fix.
  • Firefox does not start... For more information, see Firefox won "t start - find solutions.
  • Problems with connecting to Facebook... For more information on problems with Facebook, see Fix problems with Facebook games, chat and more.
  • Firefox keeps opening many tabs or windows... For more information, see Firefox repeatedly opens empty tabs or windows after you click on a link.
  • Unwanted toolbars have been installed... For more information on customizing Firefox, see Remove a toolbar that has taken over your Firefox search or home page and How to remove the Babylon toolbar, home page and search engine.

How do I prevent malware from being installed?

There are simple rules to follow in order to prevent malware from being installed on your computer:

  • Keep your operating system and other software updated: Installation of malicious software usually takes advantage of known security vulnerabilities in other programs, which may have been patched in later versions. Make sure you are using the latest version of all software you use, either by enabling the software "s automatic update feature, if available, or by checking for updates from the software provider and by using the Windows Update feature.
  • Don "t install untrusted software: Some websites offer you software to accelerate your browser, to help you search the Web, to add toolbars that make things Firefox already does. Some unwanted programs also come bundled in software packages. Usually, these programs gather information on your browsing behavior that serve only people who designed them and interfere with Firefox. Make sure you install add-ons from Mozilla "s add-on website and you uncheck unwanted programs in software wizards. Check to see if you have unwanted add-ons and disable or remove them.
  • Don "t click inside misleading pop-up windows: Many malicious websites try to install malware on your system by making images look like pop-up windows, or displaying an animation of the website scanning your computer. For more information on detecting a misleading pop-up, see Pop-up blocker settings, exceptions and troubleshooting.
  • Don "t run a fake Firefox: Download Firefox from mozilla.org/firefox.
  • Run anti-virus and anti-spyware real-time protection and scan your system periodically. Make sure your anti-virus and anti-spyware real-time protection is enabled. Scan your computer at least every month.

How do I get rid of malware?

The Wikipedia article Linux malware has information and recommendations for Linux users.

How do I get rid of malware?

Microsoft has basic free anti-virus and anti-spyware security software built-in on Windows 8 and Windows 10for Windows 7 (see What is Microsoft Security Essentials?)... If your security software hasn "t detected malware, scan your system with the free malware scanning programs listed below. You should scan with all programs because each program detects different malware and make sure that you update each program to get the latest version of their databases before doing a scan.

Warning: Anti-virus and anti-spyware software may sometimes generate false positives. Consider quarantining suspicious files rather than deleting them.

  • users complain that the website is being blocked by the browser and / or programs
  • the website is blacklisted by Google or another malicious URL base
  • there have been major changes in traffic volume and / or in search engine rankings
  • the website does not work as it should, gives errors and warnings
  • after visiting the website, the computer behaves strangely.

Malicious code often goes unnoticed for a long time, especially if it is infected with very complex malware. Such malware is usually heavily obfuscated to mislead both website administrators and antivirus programs; it constantly changes domain names to which it redirects users, thus bypassing blacklists. If none of the above symptoms are present, this is a good indicator of your server's cleanliness, although alas, not 100%; therefore, remain alert to any suspicious activity.

The most obvious sign of any malware infection is the presence of malicious / suspicious code in one or more files - mainly in HTML, PHP or JS format, and for some time now also ASP / ASPX. This code is not easy to find, it requires knowledge of at least the basics of programming and website development. In order for the reader to better understand what malicious code looks like, we present several examples of the most common infection of web pages.

Example 1: simple forwarding

The oldest and the most simple method used by cybercriminals is to add a simple HTML iframe tag to the code of HTML files on the server. The URL used to load the malicious website in the IFrame is specified as the SRC attribute; the VISIBILITY attribute of “hidden” makes the frame invisible to the user visiting the website.

Figure 1: Malicious IFrame Inside Website HTML

Another method of executing malicious script in the user's browser is to embed a link to this script in an HTML file as the src attribute in the script or img tags:

Figure 2: Examples of malicious links

Recently, there have been more and more cases when malicious code is dynamically generated and injected into HTML code by malicious JS or PHP scripts. In such cases, the code is visible only in the source view of the page from the browser, but not in the physical files on the server. Cybercriminals can additionally define the conditions when malicious code should be generated: for example, only when a user navigates to a site from certain search engines or opens a website in a particular browser.

Cybercriminals use a variety of code obfuscation techniques to trick both the website owner and the antivirus software and to obstruct the malicious code.

Example 2: "Error 404: Page Not Found"

In this example, malicious code is injected into the message template that is displayed when the specified object was not found on the server (the well-known "404 error"). In addition, a link to some nonexistent element is injected into the index.html / index.php files in order to invisibly cause this error every time a user visits an infected web page. This method can cause some confusion: the person in charge of the website receives a message that some antivirus solution has flagged the website as infected; after a superficial check, it turns out that the malicious code was found in an object that apparently does not exist; this leads to the temptation to assume (wrongly) that it was a false alarm.

Figure 3. Trojan.JS.Iframe.zs - malicious script in the 404 error message template

In this particular case, the malicious code was obfuscated. After deobfuscation, we can see that the purpose of the script is to inject an IFRAME tag that will be used to redirect users to a malicious URL.

Figure 4. Trojan.JS.Iframe.zs - malicious code after deobfuscation

Example 3: selective injection of malicious code

Similar code can be generated and attached dynamically (i.e. depending on specific conditions) to all HTML files located on the server using a malicious PHP script uploaded to the same server. The script shown in the following example checks the UserAgent parameter (which is sent by the user's browser and search bots) and does not add malicious code if the website is crawled by a bot or if site visitors use Opera browsers, or Safari. This way, users of browsers that are immune to the specific exploit used for the attack will not be redirected to that exploit. It is also worth noting that comments in the code are deliberately misleading, suggesting that this script has something to do with bot statistics.

Figure 5. Trojan.PHP.Iframer.e - code that infects a PHP script

This method can also be used in the opposite direction: cybercriminals can insert links leading to illegal, questionable or malicious content (spam, spyware, software, phishing resources) only if a search bot has entered the website. The purpose of such an attack is the so-called black optimization - a mechanism for raising the position of a cybercriminal resource in search results. Such malware usually targets popular, highly rated web portals and is quite difficult to detect since the malicious code is never shown to the average user. As a result, malicious websites get high rankings in search engines and end up at the top of search results.

Example 4: tricky obfuscation

Infecting PHP scripts can take other forms as well. Below are two examples discovered a few months ago.


Figure 6. Trojan-Downloader.PHP.KScript.a -infecting PHP script


Fig 12. Trojan-Downloader.JS.Twetti.t - malicious code injected into JS files

Finally, there is a known case of mass malware infection in which random domain names are used. If infected with this malware, you may find the following code on your website:

Figure 13. Obfuscated version of the code that redirects to a randomly generated domain

Example 6: "gootkit" and obfuscating an entire file

Obfuscated malicious code is easy to detect among the rest of the clean code, and therefore, recently, cybercriminals came up with the idea to obfuscate the entire file contents, thus making both the injected and legitimate code unreadable. It is impossible to separate the legitimate code from the malicious code, and the file can be disinfected only after it has been decrypted.

Fig. 14. File obfuscated by the "gootkit" malware

Getting rid of the first level of obfuscation is not difficult, for this you just need to change the eval () function to alert () - or print () in the case of the console - and run it for execution. The second level is a little more difficult: in this case Domain name used as a key to encrypt the code.

Fig. 15: "gootkit" - the second level of obfuscation

After decryption, you can see the malicious code following the original content of the file:

Fig. 16: "gootkit" - deobfuscated code

Sometimes the malicious part turns out to be the second version of the malicious programs discussed in the previous example and is used to generate a pseudo-random domain name for redirection.

Example 7: .htaccess

Instead of infecting scripts and HTML code, cybercriminals can use the capabilities of some files, for example .htaccess. In such files, the administrator can define access rights to certain folders on the server, as well as, under certain circumstances, redirect users to other URLs (for example, if the user comes from a browser mobile device, it redirects to mobile version website). It's not hard to guess how cybercriminals use this functionality ...

Fig. 17: malicious .htaccess

In the above example, all users who visit this website following a link in most major search engines (HTTP_REFERER parameter) are redirected to a malicious URL. In addition, this .htaccess file defines a fairly large number of browsers and bots for which no redirection is performed (parameter HTTP_USER_AGENT). Redirection also does not occur if the web page is read from the cache (referer == cache) or reloaded from the same computer (cookie parameter).

Such malware also allows for more selective infections - for example, specific IP addresses can be excluded, and when browsing websites from a specific range of IP addresses - for example, owned by the company by information security- no malicious results are generated.

Attack vectors and infection technologies

Regardless of the technology used, cybercriminals need to find a way to deliver malicious files to the server or modify files that already exist on the server. The most primitive method of gaining access to the server is by cracking the access password. To do this, cybercriminals can use a so-called brute-force attack or a limited version of it - a brute-force attack (dictionary attack). This tactic usually requires a lot of time and resources, and therefore is rarely used for mass infections of websites. More popular scenarios include exploitation of vulnerabilities and malware to steal passwords.

Exploitation of vulnerabilities in content management system / e-commerce system

Most modern web content management platforms (such as content management system (CMS), e-commerce, control panels, etc.) are imperfect and have vulnerabilities that allow others to upload files to the server without authentication. And although developers are constantly looking for such vulnerabilities, the release of patches takes a lot of time; in addition, many users continue to use older versions of programs with a lot of bugs. Most often, vulnerabilities are found, of course, in the most popular platforms such as WordPress, Joomla and osCommerce.

A well-known example of such a vulnerability is TimThumb, which has been widely exploited by cybercriminals in a variety of drive-by boot scenarios. TimThumb is a PHP module for resizing images and creating so-called graphic thumbnails, included in most open source CMS templates. The vulnerability allows files located on a remote machine to be written to the server in the cache directory. Another example is the SQL injection vulnerability in Plesk Panel (versions 10 and later), discovered in February 2012, which allows you to read databases and steal passwords that - until recently - were stored explicitly. The credentials obtained in this way were probably used in the recent massive web outbreak http://www.securelist.com/en/blog/208193624/Who_is_attacking_me; https://www.securelist.com/ru/blog/208193713/RunForestRun_gootkit_i_generirovanie_sluchaynykh_domennykh_imen.

Using spyware to steal FTP server credentials

In the most common web infections (eg Gumblar and Pegel), another method has been successful. In the first stage, cybercriminals distribute malware designed specifically to find and steal FTP usernames and passwords by checking FTP client settings or scanning network traffic. After the malware finds this registration data on the infected computer of the site administrator, the program establishes a connection to the FTP server and downloads malicious scripts or writes their infected versions instead of the original files. It goes without saying that as long as the account holder's computer is infected, the files stored on the server will be infected over and over again even after changing the registration data and restoring all content from a clean backup.

Targets of cybercriminals

What is the purpose of a website infection?

  • redirecting users to exploits to invisibly install malware on their computers;
  • redirecting users to spam, phishing and other malicious, illegal or unwanted content;
  • interception / theft of site visits / search queries.
  • promotion of malicious / illegal websites and websites containing spam (black optimization);
  • use of server resources for illegal activity.

Basically, this is nothing new: when cybercriminals infect websites, they are driven by the desire to make an indirect profit.

Methods to eliminate malicious code

What to do if your site is attacked by hackers?

First, if you see symptoms that indicate a possible infection, you should immediately deactivate the website until the problem is fixed. This is extremely important indeed, because every moment of delay plays into the hands of cybercriminals, allowing more computers to infect and spread the infection throughout. You should check the server logs for suspicious activity, such as strange requests from IP addresses located in countries that are not typical for site visitors, etc. - this can be useful for detecting infected files and determining exactly how cybercriminals gained access to the server.

But how to deal with malicious code?

Backup copy

The fastest and most reliable way to restore all server content is with a clean backup. To do this effectively, it is also necessary to perform a complete reinstallation of the software running on the server (content management system / CMF, e-commerce systems, etc.). Of course, this requires the latest, fully updated versions to be used. After these steps, no infected files should remain on the server - provided that you erased all content before restoring, and a backup was created even before the attack began.

Automatic check

If you don't have a clean backup, you have no choice but to start fighting malware. Fortunately, there are a number of automated solutions to help you find malicious code - including antivirus products and online website crawlers such as http://sucuri.net/. None of them are perfect, but in the case of well-known / common malware, they can all be quite useful. To begin with, you can check a website using several online scanners. Some of them will not only determine if your site is indeed infected, but will also point out malicious code in your files. Then you can perform a full anti-virus scan of all files on the server.

If you are the server owner, or if the server is running a security solution that you are authorized to use, you can perform server-side validation. Make sure to create a copy of your files, as some antivirus scanners do not cure infected files, but delete them! You can also download the contents of your server to your local computer and scan it with a desktop antivirus solution. The second option is preferable, since most modern desktop antivirus programs include a well-developed heuristic module. Malicious programs that infect websites are highly polymorphic: while signature analysis is almost useless to combat it, heuristics make it easy to detect.

Manual removal

If the automatic scan did not return any results and you still receive messages about the infection of your site, the only way to get rid of the malware is to find it manually and remove all malicious code. This daunting task can take a significant amount of time as it is necessary to check every file - be it HTML, JS, PHP or configuration file - for malicious scripts. The examples above are just a small part of the variety of malware for websites, so it is highly likely that the malicious code on your site will be partially or completely different from these samples. However, most modern website malware has some common features that will help in identifying the problem.

Most of all, you need to pay attention to those parts of the code that look unclear or unreadable. Code obfuscation, a technology that is commonly used, is quite unusual for any other software associated with websites. If you haven't obfuscated the code yourself, you have every reason to be suspicious of it. But be careful - not all obfuscated code will be malicious!

Likewise, not every malicious script is obfuscated, so it makes sense to look for explicit IFRAME tags and other links to external resources in all of your files. Some of these may be related to advertisements and statistics, but don't be fooled by specially crafted URLs, which can be confusing to look like well-known and trusted portals. Remember to check the boilerplate error code as well as all .htaccess files.

Grep and find are undoubtedly useful tools for finding malicious code on a server, command-line utilities that are included by default on almost all Unix-based systems. Below are examples of their use in diagnosing the most common infections:

grep -iRs “iframe” *
grep -iRs “eval” *
grep -iRs “unescape” *
grep -iRs “base64_decode” *
grep -iRs “var div_colors” *
grep -iRs “var _0x” *
grep -iRs “CoreLibrariesHandler” *
grep -iRs “pingnow” *
grep -iRs “serchbot” *
grep -iRs “km0ae9gr6m” *
grep -iRs “c3284d” *
find. -iname “upd.php”
find. -iname “* timthumb *”

Description of grep (from Linux manual): Print lines matching a pattern; the -i option means ignore case; -R stands for recursive search, and -s prevents error messages from being shown. The first of the listed commands searches files for IFRAME tags; the other three are looking for the most obvious signs of obfuscation; the rest are looking for special strings associated with the largest known website infections.

As far as find is concerned, the Linux manual states: find files in a hierarchical folder structure; "." (dot) indicates the current directory (so these commands should be run from the root directory or home directory on the server), the -iname parameter specifies the file to look for. You can use regular expressions to find all files that match certain criteria.

Of course, you always need to know what to look for - not all results will indicate an infection. It's a good idea to check the suspicious parts of the code with an antivirus scanner or try searching them on google. It is very likely that you will find some answers - for both malicious and clean code. If you are still not sure if a file is infected, it is best to deactivate the website (just in case) and seek professional advice before taking any action.

Very important!

In addition to cleaning files on the server, it is imperative to perform a full anti-virus scan of all computers used to download and manage content on the server and change all data for accessing all accounts on the server (FTP, SSH, control panels, etc.) that you support. ...

Security Basics for Websites

Unfortunately, in most cases, removing the malicious code is not enough to get rid of the infection once and for all. If your website is infected, this may indicate the existence of vulnerabilities that allowed cybercriminals to inject malicious scripts into the server; and if you ignore this problem, new infections await you in the near future. To prevent this, you need to take appropriate measures to protect the server and the computer / computers used to administer the server.

  • Use of strong passwords. Despite the triviality of this advice, it really is the foundation of server security. It is not only necessary to change passwords after each incident and / or attack on the server - they should be changed on a regular basis, for example monthly. A good password must meet special criteria, which can be found at www.kaspersky.com/passwords;
  • Regular updates. It is also necessary not to forget about regular updates. Cybercriminals often exploit vulnerabilities in software regardless of the malware's target - whether it targets PC users or websites. All programs with which you manage your server / site content should be the most latest versions and every security update should be installed as soon as it is released. Using current versions Software and timely installation of all necessary patches will help reduce the risk of an attack using exploits. A regularly updated list of known vulnerabilities can be found at http://cve.mitre.org/;
  • Regular backups. Having a clean copy of the server's content in stock will save you a lot of time and effort, not to mention the fact that fresh backups can be very useful in solving other problems, in addition to curing the infection;
  • Regular file checking. Even in the absence of obvious symptoms of infection, it is recommended to periodically scan all files on the server to detect malicious code;
  • Securing your PC. Since a significant amount of malware for websites spreads through infected PCs, the security of the desktop computer used to manage your website is one of the top priorities for website security. Continuously keeping your computer clean and safe significantly increases the likelihood that your website will also be safe and virus-free.
  • The following actions should be mandatory (but not sufficient):
    • removal of unused programs;
    • deactivation of unnecessary services and modules;
    • setting up appropriate policies for individual users and user groups;
    • setting adequate access rights to certain files and directories;
    • disabling the display of files and directories of the web server;
    • maintaining event logs that are regularly checked for suspicious activity;
    • use of encryption and secure protocols.

Malware designed to infect websites can be a real nightmare for web administrators and Internet users. Cybercriminals are constantly evolving their technology by discovering new exploits. Malware spreads rapidly over the Internet, affecting servers and workstations. It is fair to say that there is no surefire way to completely eliminate this threat. However, every website owner and every Internet user can make the internet safer by following basic safety rules and by keeping their websites and computers safe and clean at all times.

Leave your comment!

And is a comprehensive cross-site scripting tutorial.

Part One: Overview

What is XSS?

Cross-site scripting ( English Cross-site scripting) Is a code injection attack that allows an attacker to execute malicious JavaScript in another user's browser.

The attacker does not directly attack his victim. Instead, it exploits a vulnerability in the website the victim is visiting and injects malicious JavaScript code. The victim's browser displays malicious JavaScript as a legitimate part of the website, and the website itself acts as the attacker's direct accomplice.

Injection of malicious JavaScript code

The only way for an attacker to run malicious JavaScript in the victim's browser is to inject it into one of the pages that the victim downloads from the website. This is possible if the website allows users to enter data on its pages, and the attacker can insert a line that will be detected as part of the code in the victim's browser.

The example below shows a simple server-side script that is used to display the last comment on a site:

print " "
print "Last comment:"
print database.latestComment
print ""

The script assumes that the comment consists only of text. However, since direct user input is enabled, an attacker could leave this comment: "". Any user who visits the page will now receive the following response:


Last comment:

When the user's browser loads the page, it will execute everything, including the JavaScript contained within the tags ... This suggests that the mere presence of a script injected by an attacker is a problem, regardless of what specific script code is actually being executed.

Part two: XSS attack

Participants in an XSS attack

Before describing in detail how an XSS attack works, we need to identify the actors involved in the XSS attack. In general, there are three participants in an XSS attack: Web site, victim, and cracker.

  • Web site produces HTML pages for users who request them. In our examples, it is located at http: // website /.
    • Website database is a database that stores some of the data entered by users on the pages of the site.
  • Victim Is a regular website user who requests pages from him using his browser.
  • Attacking Is an attacker who intends to launch an attack on the victim by exploiting an XSS vulnerability on the site.
    • Cracker server Is a web server under the control of an attacker with the sole purpose of stealing the victim's confidential information. In our examples, it is located at http: // attacker /.

Example attack scenario

This script will create an HTTP request to a different URL that will redirect the user's browser to the attacker's server. The URL includes the victim's cookies as a request parameter, when an HTTP request arrives at the attacker's server, the attacker can extract these cookies from the request. After the attacker has received the cookies, he can use them to impersonate the victim and launch a subsequent attack.

From now on, the above HTML code will be called malicious string or malicious script... It is important to understand that the string itself is only malicious if it is ultimately processed as HTML in the victim's browser, which can only happen if there is an XSS vulnerability in the website.

How this example attack works

The diagram below shows an example of an attacker performing an attack:

  1. The attacker uses one of the website's forms to insert a malicious string into the website's database.
  2. The victim requests a page from a website.
  3. The site includes a malicious string from the database in the response and sends it to the victim.
  4. The victim's browser runs the malicious script inside the response, sending the victim's cookie to the attacker's server.

XSS types

The target of an XSS attack is always to execute a malicious JavaScript script in the victim's browser. There are several fundamentally different ways to achieve this goal. XSS attacks are often categorized into three types:

  • Stored (persistent) XSS where the malicious string originates from the website's database.
  • Reflected (volatile) XSS where the malicious string is spawned from the victim's request.
  • DOMs XSS where the vulnerability occurs in the client-side code rather than the server-side code.

The previous example shows a stored XSS attack. We will now describe two other types of XSS attacks: Reflected XSS and DOM XSS.

Reflected XSS

In a reflected XSS attack, the malicious string is part of the victim's request to the website. The site accepts and inserts this malicious string into the response it sends back to the user. The diagram below illustrates this scenario:

  1. The victim is tricked by the attacker to send a URL request to the website.
  2. The site includes a malicious string from the request URL in the victim's response.
  3. The victim's browser executes the malicious script contained in the response, sending the victim's cookie to the attacker's server.

How to successfully defend against XSS attack?

A reflected XSS attack may seem harmless, as it requires the victim to send a request on their behalf containing a malicious string. Since no one will voluntarily attack themselves, there seems to be no way to actually carry out the attack.

As it turns out, there are at least two common ways to get the victim to launch a reflected XSS attack against themselves:

  • If the user is a specific person, the attacker can send a malicious URL to the victim (for example, via email or instant messenger) and trick them into opening the link to visit the website.
  • If the target is a large group of users, an attacker could post a link to a malicious URL (for example, on his own website or on a social network) and wait for visitors to click on the link.

Both of these methods are similar, and both can be more successful by using URL shortening services to mask the malicious string from users who might identify it.

XSS in the DOM

DOM XSS is a variant of both a stored and reflected XSS attack. In this XSS attack, the malicious string is not processed by the victim's browser until the actual JavaScript of the website is executed. The diagram below illustrates this scenario for a reflected XSS attack:

  1. The attacker creates a URL containing a malicious string and sends it to the victim.
  2. The victim is tricked by the attacker to send a URL request to the website.
  3. The site accepts the request, but does not include the malicious string in the response.
  4. The victim's browser executes the legitimate script contained in the response, as a result of which the malicious script will be inserted into the page.
  5. The victim's browser executes the malicious script inserted into the page, sending the victim's cookie to the attacker's server.
What is the difference between XSS in the DOM?

In the previous examples of stored and reflected XSS attacks, the server injects malicious script into the page, which is then forwarded in response to the victim. When the victim's browser receives a response, it assumes that the malicious script is part of the legitimate content of the page and automatically executes it at page load time, just like any other script.

In the DOM XSS attack example, the malicious script is not inserted as part of the page; the only script that is automatically executed during page load is the legitimate part of the page. The problem is that this legitimate script directly uses user input to add HTML to the page. Since the malicious string is inserted into the page using innerHTML, it is parsed as HTML, causing the malicious script to execute.

This distinction is small, but very important:

  • In traditional XSS, malicious JavaScript is executed on page load, as part of the HTML sent by the server.
  • In the case of XSS in the DOM, the malicious JavaScript is executed after the page is loaded, resulting in that legitimate JavaScript page accessing user input (containing the malicious string) in an unsafe manner.
How does XSS work in the DOM?

In the previous example, JavaScript is not required; the server can generate all the HTML by itself. If the server-side code were free of vulnerabilities, the website would not be vulnerable to the XSS vulnerability.

However, as web applications become more advanced, more and more HTML pages are generated using JavaScript on the client side rather than on the server. At any time, the content must change without refreshing the entire page, this is possible using JavaScript. In particular, this is the case when the page is refreshed after an AJAX request.

This means that XSS vulnerabilities can be present not only in the server side of your site's code, but also on the JavaScript side of your site's client code. Hence, even with completely safe server-side code, the client code may still not be safe to include user input when the DOM is updated after the page has loaded. If this happens, then the client-side code will allow an XSS attack through no fault of the server-side code.

DOM-based XSS may not be visible to the server

There is a special case of a DOM XSS attack in which the malicious string is never sent to the website server: this happens when the malicious string is contained in a portion of the URL's identifier (anything after the # character). Browsers do not send this portion of the URL to the server, so the website cannot be accessed by server side code. The client-side code, however, has access to it, and thus it is possible to conduct an XSS attack through insecure processing.

This case is not limited to the fragment identifier. There is other user input that is invisible to the server, such as new HTML5 features like LocalStorage and IndexedDB.

Part three:
Preventing XSS

XSS Prevention Techniques

As a reminder, XSS is a code injection attack: user input is mistakenly interpreted as malicious code. Safe handling of input is required to prevent this type of code injection. For a web developer, there are basically two different ways performing safe input processing:

  • Coding is a way that allows the user to enter data only as data and does not allow the browser to be processed as code.
  • Validation is a way to filter user input so that the browser interprets it as code without malicious commands.

While these are fundamentally different methods of XSS prevention, they have several things in common that are important to understand when using any of them:

Context Safe handling of input needs to be done differently depending on where the user input is used on the page. inbound / outbound Secure input processing can be performed either when your site receives input (inbound traffic) or right before the site inserts user input into the page content (outbound). Client / Server Secure input processing can be done either on the client side or on the server side, each of which is needed under different circumstances.

Before explaining in detail how coding and validation works, we describe each of these points.

Handling User Input in Contexts

There are many contexts on a web page where user input can be applied. For each of them, special rules must be followed so that user input cannot "escape" from its context and cannot be interpreted as malicious code. The following are the most common contexts:

How important are contexts?

In all of the described contexts, an XSS vulnerability can arise if user input was inserted prior to the first encoding or validation. An attacker can inject malicious code simply by inserting a closing separator for this context followed by malicious code.

For example, if at some point a website includes user input directly into an HTML attribute, an attacker could inject malicious script by starting their input with a quotation mark, as shown below:

This could have been prevented by simply removing all quotes in the user input and it would be fine, but only in this context. If the input was inserted into a different context, the closing delimiter will be different and injection will be possible. For this reason, safe handling of input must always be adapted to the context where user input will be inserted.

Handling incoming / outgoing user input

Instinctively, it might seem like XSS can be prevented by encoding or validating all user input as soon as our site receives it. This way, any malicious strings will already be neutralized whenever they are included in the page, and HTML generation scripts will not have to worry about safe handling of user input.

The problem is that, as described earlier, user input can be inserted into multiple contexts on the page. And no easy way determine when user input comes into context - how it will ultimately be inserted, and the same user input often needs to be inserted in different contexts. By relying on handling incoming input to prevent XSS, we create a very fragile solution that will be error prone. (The legacy PHP magic quotes are an example of such a solution.)

Instead, handling outbound input should be your main line of defense against XSS, because it can take into account the specific context of what user input will be inserted. To some extent, inbound validation can be used to add a secondary layer of protection, but more on that later.

Where it is possible to safely handle user input

In most modern web applications, user input is handled both on the server-side code and on the client-side code. In order to protect against all types of XSS, secure input processing must be done in both server-side code and client-side code.

  • In order to protect against traditional XSS, secure input handling must be done in server-side code. This is done using some language supported by the server.
  • To protect against an XSS attack in the DOM, where the server never receives a malicious string (such as the ID fragment attack described earlier), secure input handling must be done in client-side code. This is done using JavaScript.

Now that we have explained why context matters, why the distinction between inbound and outbound input processing is important, and why safe input processing must be done on both the client and server sides, we can go on to explain. how the two types of secure input handling (encoding and validation) are actually performed.

Coding

Encoding is a way out of a situation where it is necessary that the browser interprets user input only as data, not code. The most popular type of coding in web development is HTML masking, which converts characters such as < and > in < and > respectively.

The following pseudocode is an example of how user input (user input) can be encoded using HTML masking and then inserted into a page using server-side script:

print " "
print "Last comment:"
print encodeHtml (userInput)
print ""

If the user enters the following line, the resulting HTML will look like this:


Last comment:

Because all characters with a special meaning have been masked, the browser will not parse any part of the user input like HTML.

Client and server side coding

When executing client-side coding, JavaScript is always used, which has built-in functions that encode data for different contexts.

When doing coding in your server-side code, you rely on the functions available in your language or framework. Due to the large number of languages ​​and frameworks available, this tutorial will not cover the details of coding in any particular server or framework language. However, the JavaScript encoding features used on the client side are also used when writing server side code.

Client side coding

When coding client-side user input with JavaScript, there are several built-in methods and properties that automatically encode all data into a context sensitive style:

The last context already mentioned above (values ​​in JavaScript) is not included in this list because JavaScript does not provide a built-in way to encode data that would be included in the JavaScript source code.

Encoding limitations

Even when coding, it is possible to use malicious strings in some contexts. A prime example of this is when user input is used to provide a URL, like in the example below:

document.querySelector ("a"). href = userInput

Although the specified value in the property of the href element automatically encodes it so that it becomes nothing more than the value of the attribute, this in itself does not prevent an attacker from inserting a URL that begins with "javascript:". When the link is clicked, regardless of construction, the embedded JavaScript inside the URL will be executed.

Coding is also not an efficient solution when you want users to be able to use some of the HTML codes on the page. An example would be a user profile page where a user can use custom HTML. If this plain HTML is encoded, the profile page can only consist of plain text.

In situations like this, the coding needs to be complemented by validation, which we'll get to know next.

Validation

Validation is the act of filtering user input so that all malicious parts of it are removed without having to remove all of the code in it. One of the most used types of validation in web development allows you to use some HTML elements (for example, and ) but prohibiting others (e.g.

With a properly defined CSP policy, the browser cannot download and execute malicious ‑ script.js because http: // attacker / is not listed as a trusted source. Even though the site was unable to reliably handle user input, in this case, the CSP policy prevented the vulnerability and any harm.

Even if an attacker injected code into the script code rather than linking to an external file, a properly configured CSP policy would also disallow injection into JavaScript code, preventing the vulnerability and causing any harm.

How do I enable CSP?

By default, browsers do not use CSPs. In order to enable SCP on your website, pages must contain an additional HTTP header: Content ‑ Security ‑ Policy. Any page containing this header will apply security policies at the time of loading by the browser, provided that the browser supports CSP.

Since the security policy is sent with every HTTP response, it is possible on the server to individually set the policy for each page. The same policy can be applied to the entire website by inserting the same CSP header in every response.

The value in the Content-Security-Policy header contains a string that defines one or more security policies that will apply to your site. The syntax for this line will be described later.

The heading examples in this section use line breaks and indentation for clarity; they should not appear in this heading.

CSP syntax

The syntax for the CSP header is as follows:

Content ‑ Security ‑ Policy:
directive source-expression, source-expression, ...;
directive ...;
...

This syntax has two elements:

  • Directives which are strings indicating the type of resource taken from the given list.
  • Source Expressions is a model describing one or more servers from which resources can be loaded.

For each directive, the data in the source expression determines which sources can be used to load resources of the corresponding type.

Directives

The following directives can be used in the CSP header:

  • connect ‑ src
  • font-src
  • frame-src
  • img ‑ src
  • media-src
  • object ‑ src
  • script-src
  • style-src

In addition to this, the special default-src directive can be used to provide a default value for all directives that were not included in the header.

Source expression

The syntax for creating a source expression is as follows:

protocol: // host-name: port-number

The hostname can start with *, which means that any subdomain of the provided hostname will be resolved. Similarly, the port number can be represented as *, which means that all ports will be allowed. In addition, the protocol and port number can be skipped. If no protocol is specified, the policy will require all resources to be loaded using HTTPS.

In addition to the above syntax, the source expression can alternatively be one of four keywords with special meaning (quotes included):

"none" disables resources. "self" resolves resources from the host on which the web page resides. "unsafe-inline" resolves resources contained in the page as inline