May 22, 2017

Web Application Security: 10 Best Practices

Rostyslav Stekh
Rostyslav Stekh

Protection of WEB App is of paramount importance and it should be afforded the same level of security as the intellectual rights or private property. Neglecting safety rules sometimes leads to catastrophic consequences. In this article I'm going to cover how to protect your WEB App.

1. Escaping special characters

It could be either a scammer or hacker who could leave on your website a comment or message similar to:


If you print this text directly to HTML without reviewing or debugging, the script will run on all visitors’ browsers. So, try to remove dangerous tags from the text and escape special characters.

For example, you can replace <, >, " with < > ". After editing the code, you will get the following results:


2. Cross-Site Scripting Prevention by Adding Headers to the Server

If you have an access to the server, you can add headers such as:

X-Content-Type-Options, X-XSS-Protection, X-Frame-Options, X-Content-Security-Policy, Strict-Transport-Security.

Each of them will provide the expected degree of protection. Here, let’s look at each a little more closely.

For X-Content-Type-Options, you should send the nosniff value. This is a security feature that helps prevent attacks using in response the MIME type’s replacement. More precisely, the "stylesheet" and "script" files will not be loaded unless they match the correct MIME types. You can read more here: MSDN

X-XSS-Protection: 1; mode=block. If we put this header with the same values, we’ll enable the XSS filtering. And instead of scanning the page, if an attack is detected, the browser will stop its visualization. Read more: MSDN

X-Frame-Options with the DENY value prohibits the page to be displayed in a frame, so that you can not use the page on other websites. Read more: MSDN

X-Content-Security-Policy – the value of this header must be formed based on the technical requirements for the website functionality, in accordance with w3

Strict-Transport-Security: max-age=expireTime, the time, in seconds, for which the browser should remember that this site has to be accessed only using HTTPS. This header lets a web site inform the browser that it should never load the site using HTTP and should automatically convert all attempts to access the site using HTTP to HTTPS requests instead. Read more: MSDN

3. Cross-Site Request Forgery (CSRF) Prevention by Using a Key

CSRF is a type of attack that uses disadvantages of the HTTP protocol and forces the end users to execute unwanted actions on websites. If the victims use a malicious website created by a CSRF attacker, they perform an undesired function. For example, the target victims could send without knowledge a request to another server where the attacker compromises user data and associated functions, and performs some kind of harmful operations.

Any requests for data changes on the server as well as those that return personal data ought to be protected against the CSRF attacks.

One method is to transfer the secret key with each user request. This key should be among the POST, PUT, PACH, UPDATE options that an end-user sends. Before any action, the server checks the key.

4. Cross-Site Scripting Prevention by Using JavaScript

If there is an access to the client-server side, then you can change the js-script code. The essence of this method is to rewrite some DOM methods – particularly, the write method of a class document. This will make the creation of i-frames or other html-code for the XSS attacks or the placement of malicious code impossible. To do this, you shave to add the code:

HTMLDocument.prototype.defineGetter("write",function(){return null});

5. Preventing an authentication hacking attack

Everything is simple here: the attackers try to find passwords or session ID's and get access the desired information.

To protect yourself, you should do the following:

  • Hash passwords
  • Transfer session id in cookies (do not show session ID's in the URL)
  • Use one session (when the user logs in, do not restore the old session, and when the user logs off – clear the session)

6. Preventing DDoS attacks

Denial of Service is an attack on a computer system with an intention of making computer resources inaccessible to users.

In fact, there is no way out to stop DDoS attacks. However, the consequences of DDoS attacks can be significantly reduced by properly configuring the router and firewall, and if you are constantly making analysis of anomalies in a network traffic.

You can prepare yourself for this situation:

  • All servers that have direct access to the external network must be prepared for simple and fast remote work. A big advantage will be the presence of an additional administrative network interface through which you can get an access to the server if a main channel is used.
  • The software that is used on the server must always be up to date. All holes are closed – the updates are installed. This will protect you from DoS attacks and bugs in services.
  • On the closest step to the server – the nearest router – must be installed a traffic analysis system (Netflow) which will allow you to learn in time about the attack and to carry out all the measures to prevent it.

7. Use Cookies securely

Куки є дуже зручні для користувачів і для того щоб захиститися від взлому за їх допомогою потрібно: Ніколи не використовувати куки для зберігання високочутливий або критично важливої інформації. Наприклад, не використовувати куки для запам'ятовування паролів користувачів, так як це робить його неймовірно легко для хакерів, щоб отримати несанкціонований доступ. Потрібно шифрувати інформацію, яка зберігається в куки, які ви використовуєте.

To protect your application against attacks based on cookies vulnerabilities and to keep applications secure, you may:

  • Never use cookies to store highly sensitive or important information. For example, do not use cookies to remember passwords. Otherwise, it may allow hackers to gain unauthorized access.
  • Encrypt the information that is stored in the cookies you are using.

8. Set up cookies (to be secure)

To correctly use the cookies, they must be properly configured, so that they do not involve any risks to the user.

You have to set a reasonable expiration date for cookies. Of course, it's nice to know that cookies will remain in effect for the user for several months in a row, but the reality is that each of them represents a security risk.

In the server header settings, specify the Set-Cookie header with the HttpOnly parameter. And each of the cookies with this parameter will be available only for the server, but not for the client code (JS/VBS). This will protect against cookie-theft attacks.

9. Safe connection

Here I will tell you how to improve connection security:

  • Change HTTP to HTTPS
  • Apply and follow the content security policy
  • Use TLS or SSH

TLS is a communication protocol that allows the client-server applications to communicate on the network while preventing unauthorized access and providing security communications that are not being tapped and recorded.

10. Server security

Here, I will tell how to set the server for safe operations.

  • First, you need to update the server to latest operating system, then:
  • Install Fail2ban – it is a daemon that monitors the attempts to login into the server, and it blocks suspicious activities, if any occur. It contains the basic configurations.
  • Authorize on the server with the ssh key. To disable authorization, you need to enter a password. Once the user adds the key to a program, the system authorizes the user to log in.
  • Install Firewall. Allow to operate through the required ports and close all the rest ports.
  • Enable automatic updates for the operating system security – this will allow not controlling the status of a system and closing all the gaping holes in the safety.
  • Install and configure Logwatch – it is a daemon that monitors the server logs and sends them to an email. This is useful as you can perform additional checks of the server and prevent all unauthorized access to it.

More information can be found here.


If you complete all of the above requirements, the web app will be fairly secure. However, you can never be 100 percent sure. Always keep the security system updated and monitor the WEB security trends.

More thoughts

Jan 28, 2017Technology
Creating a site preview like in slack (using aiohttp)

In this article we will write a small library for pulling metadata and creating a preview for a site just like Slack does.

Igor Tokarev
Igor Tokarev
Feb 18, 2010Technology
Business logic in models

In my recent project there was a lot of data business logic, so I had to organize this code somehow. In this article I'll describe a few hints on how to it.

Vladimir Sidorenko
Vladimir Sidorenko
May 12, 2010Technology
Twitter API, OAuth and decorators

In my current project I had a task to use twitter API. Twitter uses OAuth for authentication, which is pretty dreary. To avoid fiddling with it all the time, I've moved authentication to decorator. If key is available - nothing happens, just view is launched as usual. It's convenient that there's no need for additional twitter settings in user profile. Code is in article.

Vladimir Sidorenko
Vladimir Sidorenko
Jul 27, 2017Technology
How to Deploy Django app with AWS Elastic Beanstalk?

In this article I'll show you how to deploy Django application to AWS Beanstalk.

Rostyslav Stekh
Rostyslav Stekh
Jun 25, 2011Technology
Ajax blocks in Django

Quite often we have to write paginated or filtered blocks of information on page. I created a decorator that would automate this process.

Vladimir Sidorenko
Vladimir Sidorenko
Feb 18, 2010Technology
User profiles with inheritance in Django

Usually users' profiles are stored in single model. When there are multiple user types, separation is made by some field like user_type.Situation is a little more complicated when different data is needed for each user type.In this article I'll describe how I solve this task.

Vladimir Sidorenko
Vladimir Sidorenko