A token of gratitude: Prevent replay attacks on your website

harden-websites-against-hacksReplay 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.

token_1

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

token_2

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

token_3

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

token_4

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.

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.

token_5

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

token_6

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.

token_7

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.

token_8

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:

token_9

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 abovementioned 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.

token_10

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.

token_11

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.

token_12

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

token_13

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.

token_14

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.

token_15

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

token_16

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.

7 COMMENTS

  1. 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?

  2. Ben, nice idea for a tough problem. The thing is that if a perpetrator captures the response with the next token, he can use that to hijack the session.

    • Good point Yaron. However, session hijacking is a totally different beast. For the sake of keeping the article brief, I kept it focused on replay attacks.

  3. If you’re just trying to prevent replay attacks, just set an ever-changing token COOKIE. (Your session id is in a cookie, so this will be a second cookie.)

    There’s no need to input a hidden fields in all your forms. And it avoids problems with concurrent windows/tabs, AND it avoids having your session accumulate a large amount of previous tokens to remember.

    • Good point. In fact, as mentioned in the article, the point is to include some kind of token that is set and changed at the server. Whether the token is embedded in a cookie of a hidden field is a matter of preference. What’s important that it only remains valid for the duration of one back-and-forth between the client and server so that a malicious party can’t spoof or repeat a request.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.