# 防止重放攻击_如何防止您的网站上的重放攻击

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.

客户端通过键入URL或页面或单击链接来发出GET请求。
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.

服务器生成一个随机令牌。 随后，它将令牌的副本存储在会话中，并将令牌的副本嵌入到发送给客户端的响应的<form>标记中。
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.

客户端处理内容，然后向服务器发送POST请求，例如，当用户单击包含随机生成的令牌的按钮时。
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.

服务器使令牌无效，并返回到步骤2，在此它用新的随机令牌来表示响应。

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.

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

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

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

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. 问题是，如果刷新页面，它将重新发布您的数据并重复上一个请求，服务器将顺利处理它。 现在想象一下，如果您刚刚进行了一次重要的$ 1,000,000交易并且无意中按下了键盘上的F5键。 或更糟糕的是，某些恶意用户拦截了您的请求，发现这是一笔付款交易，然后重复执行以窃取您的资金并吞噬您。

## 解决方案 (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.

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

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.

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.

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:

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.

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.

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.

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

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.

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.

Next, we will alter the SessionHiddenToken property to use the TokenId property instead of using the Page.Title 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.

更精确地说，将为每个会话生成无限数量的令牌ID(发送到每个会话的GET请求数量)。 可以通过实现堆栈或缓存机制来解决此问题，该机制将在超出数量限制或在特定持续时间内不使用它们时弹出较旧的ID。 我将把实施留给您。
• 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.

默认的随机数生成器不是您所说的最安全，最可靠的随机性源，精明的黑客可能能够预测令牌的序列。 但是，如果您使用的是SSL加密，则无论如何他们将无法获得令牌。

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.

04-19 1184
06-01 4855
01-07 3433
11-06 727
08-17 4646
08-31 1036
08-01 1220
10-22 1434

### “相关推荐”对你有帮助么？

• 非常没帮助
• 没帮助
• 一般
• 有帮助
• 非常有帮助

©️2022 CSDN 皮肤主题：编程工作室 设计师：CSDN官方博客

1.余额是钱包充值的虚拟货币，按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载，可以购买VIP、C币套餐、付费专栏及课程。