Web
Article

How to Prevent Replay Attacks on Your Website

By Ben Dickson

Preventing replay attacks

This article was originally published at Ben’s Tech Talks site.

Replay attacks, in which attackers intercept and resend network packets that do not belong to them, are extremely dangerous and can in some cases cause serious damage. What makes these kinds of attacks even more noisome is that they can even be staged on encrypted communication channels without gaining access to the decryption keys. Attackers only have to eavesdrop on your line and have a general knowledge of what task a specific set of packets are performing, and by resending those packets or requests, they will be able to disrupt your communications or cause more damaging effects.

In this article, I’ll show you a basic, easy-to-implement method that will prevent replay attacks on your website. It will also have the side benefit of preventing the annoying effects of confused users repeating their last POST request by constantly refreshing their browser at the wrong time.

This is far from a complete solution. It has flaws and pending issues, but it gives you a general view of how tokens and simple protocols can enhance security in your websites. Sample codes and implementation are done in ASP.NET and C#, but the concept can be deployed on any other platform or programming language.

The One-time Token Concept

The idea behind the solution that will be offered in this post is to tie every HTTP response to a token string which will be valid only for the next post request. Here’s a simple breakdown of the steps involved:

  1. The client makes a GET request by typing the URL or a page or by clicking on a link.
  2. The server generates a random token. Subsequently, it stores a copy of the token in the session and embeds a copy of the token in the <form> tag of the response it sends to the client.
  3. The client processes the content, and sends a POST request to the server, say when the user clicks on a button, which contains the randomly-generated token.
  4. The server receives the request and proceeds with processing it only if the attached token is equal to the one stored in the user’s session.
  5. The server invalidates the token and returns to step 2, where it formulates the response with a new random token.

In this manner, even if a critical request sent to the server is intercepted by a malicious user, it cannot be repeated because the token it contains is no longer valid after the request is sent to the server. The same goes for the scenario where a careless user mistakenly presses F5 on the keyboard and resends the request after posting information to the server.

The Test-bed

In order to implement the one-time token concept, we’re going to create a sample page that contains a simple textbox and a submit button. We’ll also throw in a label control to display the test output.

simple textbox and button code

The code behind will be a simple snippet that displays the time of the submission plus the data contained in textbox.

time of the submission plus the data contained in textbox

This is the output of the page after the initial GET request

output after the initial GET request

After submitting the page, the output will look like this:

output after submission

The problem is, if you refresh your page it will re-POST your data and repeat the last request, and the server will process it without a hitch. Now imagine if you had just made a critical $1,000,000 transaction and inadvertently pressed F5 on your keyboard. Or worse, some malicious user intercepts your request, figures out it’s a payment transaction, and repeats it in order to siphon your funds and spite you.

Preventing replay attacks

The Solution

In order to prevent a POST request from being repeated, we update the markup to add a hidden field, which will store the token.

adding a hidden field

Next, we will create a function that generates a random token and embeds it both in the hidden field and the session collection.

random token

Afterwards, we change the Page_Load() function to only display the posted data if the posted token is equal to the one stored in the session.

change the Page_Load() function

Finally, we override the OnPreRender() function to generate a new token before the final output is sent to the client. This is what makes it a one-time token, because it’s renewed every time a new request is sent.

override the OnPreRender() function

Now when you submit the form by clicking on the button, it works just as it did before. But if you try to simulate the replay attack by refreshing the page, you’ll get the following error because the token that is sent with the form is no longer equal to the one stored on the server:

error due to incorrect token

This way, we can distinguish valid button-click submissions from falsely-repeated requests.

Refining the Code

Although this code fixes the replay attack problem for your page, it has several issues that need to be addressed:

  • It has to be repeated across all pages
  • It will not work if you have several tabs open on the same website, because the token is being shared across requests
  • It’s downright ugly

As a fanatic Object Oriented Programming (OOP) enthusiast, I’m always looking for opportunities to refactor and refine code by leveraging the power of this most awesome programming paradigm.

In order to address the above-mentioned issues, the first thing we do is to define a class that will encapsulate the token generation functionality. We’ll call the class TokenizedPage and will derive it from System.Web.UI.Page in order to be able to use it for pages in the future.

calling the class TokenizedPage

Next, in order to make the code more readable and manageable, we encapsulate the page token and the session token into two different properties that we add to the TokenizedPage class. In order to make the code easily portable in web pages, we will use the ViewState collection instead of the hidden input field to store the page token. We also use the Page.Title property as the key for storing the token in the session. This will improve our code and will partially address the second issue, which would limit the use of our site to a single tab in the browser. By applying this change, we’ll be able to have separate pages of the site open in different tabs, but we won’t be able to have several instances of the same page open in separate tabs, because they’ll still be sharing tokens. This issue will be addressed later.

encapsulating  page and session tokens

Next, we add a read-only Boolean property named IsTokenValid, which follows the example of other Page properties such as IsPostBack and IsValid. The purpose of this property is to make sure the page token is equal to the session token.

adding IsTokenValid

Finally, we add the GenerateRandomToken() function and the override of the OnPreRender() event as was done in the test-bed.

GenerateRandomToken and OnPreRender

Now, in order to use the one-token pattern, all we need to do is to create a new page, derive it from TokenizedPage and use the IsTokenValid whenever the one-time token is needed.

IsTokenValid

Much better.

Making it Even Better

One of the problems with this code is that if you have two tabs in your browser pointing to the same page, posting one will invalidate the token of the other, since they’re using the same session token key. This can be addressed by adding a token ID which will make sure each request-response sequence happening in one tab will use its own set of unique tokens and will not interfere with other requests on the same page. The first order of business is to go back to the TokenizedPage class and add a TokenID property. This property generates a random ID the first time it is called in the initial GET request and stores it in the ViewState collection for future reuse.

adding a TokenID property

Next, we will alter the SessionHiddenToken property to use the TokenId property instead of using the Page.Title property.

using the TokenId property

The cool thing is that since we had used abstraction and encapsulation principles (another big shout out to the benefits of OOP), we don’t need to make any other change and the new mechanism will work with all pages that we’ve derived from TokenizedPage.

Remaining Issues

This is about it for the one-time token pattern. There are two issues that remain:

  • An unlimited number of token IDs will be generated for each session (the number of GET requests that is sent to each session) to be more precise. This can be addressed by implementing a stack or cache mechanism that pops older IDs when a number limit is exceeded or when they become unused for a specific duration. I’ll leave the implementation to you.
  • The default random number generator is not what you would call the most secure and reliable source of randomness and a savvy hacker might be able to predict the sequence of tokens. However, if you’re using SSL encryption, they won’t be able to get a hold of the token anyway.

Do you have any enhancements to add or would like to share its implementation in another platform and programming language? Please leave a note in the comments section below.

  • AMA3

    Why not store the nonce token in a cookie instead of the data? Then, you’d only need to keep track of one token on the server, and no matter which tab sends the next request, it should have the correct token in the cookie.

    • Ben Dickson

      The entire point is to track different tabs separately, since each tab might have its own sequence of postbacks with the server and using a single cookie to track all tabs that are using the same site will cause crossfire between them.

      • AMA3

        I can see how that would be important when you’re using the tokens to maintain state. However, if the purpose is simply to to prevent replay attacks (the subject of this article), then it seems to me that separate tokens for different tabs would be an unnecessary complication.

        • Ben Dickson

          In fact this technique enables you to hit two birds with one stone. You get the added level of security without causing disruption in the user experience. It wouldn’t be fair to force users to limit their use of your website to a single tab just because you don’t want to go the extra step of adding ViewState level tokens.

  • Abi

    suppose a hacker gained passwords and email a/c. okay untill that session will expire that hacker can’t use our data but after that mean (with an initial request that can use our data to be an authorized user).how can we solve this issue

    • Ben Dickson

      That is a topic that is out of scope of this article, which deals with replay attacks. But to answer you briefly:
      1- How would the hacker gain access to the credentials? It would be impossible to do so by eavesdropping on your site traffic if you have a safe HTTPS connection and do not exchange email/password through the query string.
      2- In any case, regardless of how the credentials are obtained, the first step to protect against impersonation attacks and account hijacks would be to implement 2FA on your website. That would require new and anomalous logins to verify themselves through some other means such as a fob, a mobile app notification, or an SMS (this last one is not totally safe BTW).
      Hope that helps.

  • Jaime Baum

    Hi Ben, awesome article. In my case I’m more interested in the “bonus” benefit which takes care of the case where the user inadvertently re-submits the form. But preventing Replay Attacks along the way is of course very welcome too. Would you mind to share a sample Project?

    • Ben Dickson

      Sure. You’ll have to contact me through my blog if you’re interested in getting more details.

Recommended

Learn Coding Online
Learn Web Development

Start learning web development and design for free with SitePoint Premium!

Instant Website Review

Use Woorank to analyze and optimize your website to improve your website to improve your ranking!

Run a review to see how your site can improve across 70+ metrics!

Get the latest in Front-end, once a week, for free.