How to protect your web application: basic tips, tools, useful links
Publicly available web applications are interesting for hackers as resources or earning tools. The range of application of information obtained as a result of hacking is wide: paid access to a resource, use in botnets, etc. The identity of the owner is not important, as the process of hacking is automated and put on stream. The cost of information is proportional to the fame and influence of the company.
If you set a goal, you will find a vulnerability in the application. In the report on hacker attacks on sites for 2016 Google experts reported that the number of compromised resources increased by 32% compared to 2015, and this is not the limit. Remember this and throw away the misconceptions about the impregnability of their web resources when planning work on information security.
The tips described below will help you to understand and close the priority problems of the technical protection of the site.
TIPS FOR PROTECTING WEB APPLICATIONS FROM HACKERS
Use security analysis tools
This is what white hackers use in their work. Before searching for vulnerabilities manually, check the application with automated tools. They perform penetration tests, try to crack it, for example with an SQL injection.
Below is a selection of free tools.
Applications and frameworks
- OpenVAS scans network nodes for vulnerabilities and allows them to manage vulnerabilities.
- OWASP Xenotix XSS Exploit Framework scans the resource for XSS vulnerabilities.
- Approof from Positive Technologies checks web application configuration, scans for vulnerable components, unprotected sensitive data, and malicious code.
- SecurityHeaders.io checks for the presence and correctness of server response headers responsible for web application security.
- Observatory by Mozilla scans the resource for security problems. In addition to its results, when selecting the appropriate option, it collects and adds analytics from third-party security analysis services to the report.
- One button scan scans for vulnerabilities components of the resource: DNS, HTTP headers, SSL, sensitive data, used services.
- CSP Evaluator checks the correctness of content security policy (CSP) and XSS resistance.
- SSL Server Test performs web server SSL configuration analysis.
- ASafaWeb checks for common configuration vulnerabilities in sites written in ASP.NET.
The results of automated tests are confusing because they show all sorts of potential threats. But an explanation is attached to each detected problem. First of all, analyze and correct the critical comments.
Once the recommended security changes have been made to the application, scan again to make sure that the measures taken are correct.
If automatic checking is not enough, try to manually hack your resource by changing the POST and GET request values. A debugging proxy server (like Fiddler) can help here as it intercepts HTTP request values between browser and server. Pay special attention to forms — try to bypass validation to implement XSS injection.
If the site has pages that are only available after authentication, try to impersonate another user. To do this, change the URL settings (e.g. user ID) or Cookie values.
PROTECT USER DATA WITH HTTPS
HyperText Transfer Protocol Secure (HTTPS) is an HTTP extension that supports encryption and protects user data during transmission on the Internet. HTTPS guarantees the integrity and confidentiality of communication with the server. In March this year, the popularity of HTTPS reached a tipping point, and soon its use will become the “norm” rather than the exception as it used to be.
Use HTTPS when users transmit personal information to the server: credit card information, personal data, and even the addresses of pages visited. If a cookie is set when sending data from an authorization form, which is then sent each time a request is made to the server, an attacker may receive it and spoof the request to the server. As a result, he will intercept the user session. To prevent this, use HTTPS on all pages of the site.
It’s simple: SSL certificate is generated free of charge (for example, on Let’s Encrypt), for most platforms there are tools for automatic certificate obtaining and installation. All that remains is to enable HTTPS support on the server.
It is noteworthy that Google has announced plans to provide sites that use a secure connection with advantages in search results. This is a gingerbread. The whip will be warnings about insecure connections in browsers that will grow in number. HTTP is a thing of the past, so it’s time to switch to HTTPS.
If HTTPS is already configured, it is good practice to use HTTP Strict Transport Security (HSTS), a server response header that denies the domain the use of an insecure connection.
UPDATE THE SOFTWARE
This is vital for web application security. Hackers regularly detect and immediately apply new vulnerabilities in operating systems and other software: HTTP servers or content management systems (CMS).
If the resource is located on the server of the hosting provider, the installation of updates for the operating system is a part of the service package. Otherwise, you need to update the operating system yourself.
If the resource runs on a third-party engine (CMS or forum), install security patches immediately after release. Most developers inform about updates through a mailing list or RSS feed with a description of fixed problems. WordPress and Umbraco also notify you about available updates when you log in to the control panel.
Many developers use package managers (like Composer, NPM or RubyGems) to install dependent components for applications. These packages also detect vulnerabilities, so keep an eye on their updates. Use tools like Gemnasium to automatically get notifications about security problems in project packages.
PREVENT SQL INJECTIONS
SQL injection is the execution of an arbitrary query to the application database using a form field or URL parameter. If the standard Transact SQL language is used, it is possible to insert malicious code. As a result, table data will be obtained, modified, or deleted. To prevent this, use parameterized queries, which are supported by most web programming languages.
Consider a query:
SELECT * FROM table WHERE column = 'parameter';
If an attacker changes the parameter value to ‘ OR ‘1’=’1, the query will take the following form:
SELECT * FROM table WHERE column = '' OR '1'='1';
Since ‘1’ is equal to ‘1’, the attacker will get access to all data in the table. This will allow an arbitrary query by adding an SQL expression to the end.
The vulnerability of this query is easily fixed with parameterization. For example, for an application written using PHP and MySQLi it looks like this:
$stmt = $pdo->prepare('SELECT * FROM table WHERE column = :value');
$stmt->execute(array('value' => $parameter));
PREVENT CROSS-SITE SCRIPTING
Cross-site scripting (XSS) — a type of attack on web resources, which consists of the introduction of malicious code into the page of the site, which is executed on the user’s computer, changes the page, and passes stolen information to the attacker.
Modern web applications are particularly vulnerable to this type of attack, where pages are built from user-generated content interpreted by front-end frameworks such as Angular and Ember. These frameworks have built-in protection against cross-site scripting, but mixed content generation on the server and client sides creates new complex attacks: implementation of Angular directives or Ember helpers.
When checking, focus on user-generated content to avoid incorrect interpretation by the browser. This is similar to protection against SQL injection. When generating HTML code dynamically, use special functions to modify and retrieve attribute values (e.g. element.setAttribute and element.textContent), as well as templates that automatically perform special character screenings.
The Content Security Policy (CSP) is another tool to protect against XSS attacks. CSP — server headers that define a white list of sources from which data uploading for different resource types are allowed. For example, prohibiting scripts from running from a third-party domain or disabling the eval() function. Thanks to CSP policies, even when embedding malicious code into a page, its execution becomes impossible. The official Mozilla website has a CSP manual with configuration examples.
CHECK AND ENCRYPT PASSWORDS
Store passwords as hashes, and it’s better to use one-way hashing algorithms such as SHA. In this case, hash values are compared for user authentication. If an attacker breaks into a resource and obtains hashed passwords, the damage will be reduced by the fact that the hash has a permanent effect and it is almost impossible to obtain the source data from it. But hashes for popular passwords are easy to crack with the dictionary, so also use the “salt”, unique for each password. Cracking a large number of passwords becomes even slower and computationally expensive.
As for validation, set a limit on the minimum length of a password and make sure it matches the login, e-mail, and website address.
Fortunately, most CMSs provide tools to manage security policies, but to use “salt” or set a minimum password complexity, sometimes additional configuration or installation of a module is required. When using .NET, it is worth applying the membership providers, because they have a built-in security system with a lot of settings and ready elements for authentication and password change.
CONTROL THE FILE DOWNLOAD PROCESS
Uploading files to the website by the user, even if it is just a change of avatar, carries a threat to information security. The uploaded file, which at first glance looks harmless, may contain a script and when executed on the server will open access to the site to the attacker.
Even if the type limit is set (e.g., only images), you should treat files uploaded by users with suspicion. An extension or MIME type is easy to spoof, reading the header or using image size check functions does not give a 100% guarantee, in most image formats it is possible to embed PHP code that will be executed on the server.
To prevent this, prohibit users from executing downloaded files. By default, web servers do not try to execute files with image extensions, but you should not rely solely on an extension. There are known cases where the image.jpg.php file has bypassed this check.
WAYS TO RESTRICT ACCESS:
- rename or change file extensions at upload;
- change permissions, for example, to chmod 0666;
- create a .htaccess file (see example below) that will only allow access to specified file types.
deny from all
<Files ~ "^\w+\.(gif|jpe?g|png)$">
allow from all
A safer way is to deny direct access to downloadable files by placing them, for example, outside the root folder of the site. However, in this case, you will need to create a script (or an HTTP handler in .NET) to extract the files from the closed part and output them to the user.
<img src="/imageDelivery.php?id=1234" />
// Extract image file name by ID ($_GET["id"]) from the database.
// Transmit the image to the browser
Measures to protect web applications for owners of their own servers:
- Set up a firewall, including blocking unused ports.
- If you have access to the server from the local network, create a demilitarized zone (DMZ), allowing access from the outside world only to ports 80 and 443.
- If you do not have access to the server from the local network, use protected methods (SFTP, SSH, etc.) to transfer files and manage the server from the outside.
- If possible, allocate a separate server for databases, which will not be directly accessible from the outside world.
- Restrict physical access to the server.
KEEP TRACK OF ERROR MESSAGES
Be careful what you see in the application error messages. Report the bug reports to the user in as concise a manner as possible which excludes any technical information. Keep detailed information in the server log files. After all, having complete information, an attacker can easily perform complex attacks like SQL injection.
To keep your hand on the pulse of the project, install an error-monitoring system. For example, Sentry, which automatically receives errors from handlers in the application code and through a form from users, and also provides a panel to manage them in real-time.
CHECK INCOMING DATA
Control the data received from web forms, both on the client and server sides. Simple errors such as a blank mandatory field or text entered in a numeric field are checked in the browser. These checks are bypassed, so server-side controls are mandatory. The absence of server-side checks leads to the exploitation of injections and other types of attacks by an attacker.
ALLOCATE ACCESS RIGHTS TO FILES
File permissions define who and what can do with it.
On *nix systems, files have 3 access options, which are presented as numbers:
- “Read” (4) — read file content;
- “Write” (2) — change of file content;
- “Execute” (1) — program or script execution.
To set multiple resolutions, it is enough to add their numerical values:
- “Read” (4) + “Write” (2) = 6;
- “Read” (4) + “Write” (2) + “Execute” (1) = 7.
In the distribution of rights users are divided into 3 types:
“Owner” (owner) — the creator of the file (we change, but there can be only one);
“Group” (group) — a group of users who get permissions;
“Others” (others) — the rest of the users.
Setting the owner of reading and write access rights, the group — to read, etc. — access denial looks like this:
Final presentation: 640.
The same is true for directories, but the “execute” flag means to make it a working directory.
When installing CMS solutions, they are usually installed correctly from a security point of view. However, it is often advised on the Internet to solve the problems of permissions by installing all files with values 666 or 777.
This advice helps to solve the problem but opens a serious vulnerability because everyone has the right to modify (insert malicious code) or delete files on the server. Allocate access rights to the files on the server according to the users’ needs.