How to design and implement a lightweight open API gateway for replay attack and defense

The article addresses: blog.piaoruiqing.com/2019/08/11/…

preface

The interface design in the previous article “Open API Gateway Practices (I)” mentioned that timestamp and nonce are used to prevent replay. This paper discusses replay attack and its defense. Start with two questions:

  • What is a replay attack
  • How do I defend against replay attacks

What are Replay Attacks?

What is a replay? Here’s an example:

Open your browser’s debug tool and visit a website, find a request in the Web tool and right-click Replay. As shown in figure:

The above replay operation is a common method in interface debugging. This operation allows us to skip the authentication information generation process and directly launch multiple valid requests.

Replay attack, also known as replay attack or replay attack, is a common attack method used by hackers. In this attack, the attacker sends the received data of the target host to deceive the system. It is mainly used for identity authentication and destroys the correctness of authentication.

Here’s an easy-to-understand example:

  • The server provides A payment interface. User A requests the server to initiate A 5 yuan payment operation (with signature and encryption), and the server receives the data and correctly transfers the money to user B.
  • However, this request was intercepted by hackers (probably done by user B ( ̄▽ ̄)”), and the hacker sent the request to the server intact, and the server made the wrong payment to user B for many times (of course, these are all built on the premise that the server did not take preventive measures such as the payment, and the security level is low).
  • Although the request initiated by A is signed and encrypted, B does not need to crack the data, but simply willSame dataRepeated sending to the server can achieve the purpose of spoofing.

Simulate replay attacks

The experiment equipment

The serial number The name of the The number of note
1 The server 2 10.33.30.101 – Real server

10.33.30.100 – Forge the server
2 The domain name 1 Replay-test.piaoruiqing.com (10.33.30.101)
3 DNSThe server 1 Used to simulate theDNShijacked

The experimental steps

  1. Start the server, request the interface and receive the response data.
  2. DNS hijacking (modifying DNS server address in router to simulate hijacking) and intercepting request data.
  3. Repeated sending of intercepted data to the server (replay attack).

The process records

The preparatory work

For DNS configuration, replay-test.piaoruiqing.com points to the IP address of the server on the Intranet. Start the server.

Normal request

Make a normal request with postman, where the signature has been generated in pre-request-script.

DNS hijacking to intercept data

Modify the dnsmasq configuration on the Intranet, and point the domain name replay-test.piaoruiqing.com to the forged server 10.33.30.100.

The request to replay-test.piaoruiqing.com is then sent to a fake server (10.33.30.100) to manually save the requested data. Because the request is signed and the attacker does not have a private key, the request cannot be tampered with, but a replay attack can be made. As shown, the forged server has successfully received the request data:

[Copyright Notice]


This article was published on
Park Seo-kyung’s blog, allow non-commercial reprint, but reprint must retain the original author
PiaoRuiQingAnd links:
blog.piaoruiqing.comFor negotiation or cooperation on authorization, please contact:
[email protected].

Replay request

Using the data saved in the previous step, send the request directly to the real server (with signed data). As shown in figure:

In fact, signature, encryption and other methods cannot defend against replay attacks, because the data intercepted by the attacker is the correct request data. Even if the content cannot be cracked, the attacker can replay the original data sent to the server to achieve the purpose of deception.

How do I defend against replay attacks

Baidu encyclopedia

  1. Add random number: The authentication parties do not need time synchronization and remember the used random number. If a packet contains a previously used random number, the authentication party considers the packet as a replay attack. The disadvantage is that the used random numbers need to be saved. If the recording period is long, the saving and query cost is high.

  2. Timestamp: This method has the advantage of not saving additional information. The disadvantage is that both authentication parties need accurate time synchronization. The better the synchronization is, the less likely the authentication parties are to be attacked. However, when the system is large and spans a wide area, it is not easy to achieve accurate time synchronization.

  3. Sequence number: Both parties add a progressively increasing integer to the packet. As long as a discontinuous sequence number (too large or too small) is received, the replay threat is identified. The advantage of this method is that it does not need time synchronization and saves less information than random number method. The disadvantage is that once the attacker decrypts the packet successfully, he can obtain the serial number and deceive the authentication end by increasing the serial number each time.

In practice, 1 and 2 are often used together to determine whether the random number exists within the validity period of the timestamp, and discard the random number outside the validity period.

Replay attack defense practice

We adopt the way of timestamp + random number to implement a simple replay attack interceptor. The timestamp and random number complement each other. It can verify whether the request is replayed or not by checking whether the random number exists in the cache within the time validity range, and verify whether the request is replayed or not by using the timestamp after the cache is invalid (the cache validity time and the time range are consistent). As shown in figure:

The code is as follows:

@Resource
private ReactiveStringRedisTemplate reactiveStringRedisTemplate;

private ReactiveValueOperations<String, String> reactiveValueOperations;

@PostConstruct
public void postConstruct(a) {
    reactiveValueOperations = reactiveStringRedisTemplate.opsForValue();
}

@Override
protected Mono<Void> doFilter(ServerWebExchange exchange, WebFilterChain chain) {
    // ATTRIBUTE_OPEN_API_REQUEST_BODY 'is stored by the previous filter
    OpenApiRequest<String> body 
        = exchange.getRequiredAttribute(ATTRIBUTE_OPEN_API_REQUEST_BODY);
    if(! ObjectUtils.allNotNull(body, body.getTimestamp(), body.getNonce())) {return fail(exchange);
    }
    Long gmt = System.currentTimeMillis();
    / / (a)
    if (gmt + effectiveTimeRange < body.getTimestamp() || 
        gmt - effectiveTimeRange > body.getTimestamp()) {
        return fail(exchange);
    }
    / / (2)
    return reactiveValueOperations.setIfAbsent(MessageFormat.format(
            KEY_REPLAY_NONCE, body.getAppId(), body.getNonce()),
            String.valueOf(System.currentTimeMillis()),
            Duration.ofMillis(effectiveTimeRange * 2L))
        .log(LOGGER, Level.FINE, true)
        .flatMap(approved -> approved ? 
                 chain.filter(exchange) : fail(FORBIDDEN, exchange)
            );

Copy the code
  • (一): Requests that exceed the time range will be rejected.
  • (二): The cache expiration time is equal to the valid time span. If the random number already exists in the cache, the cache is rejected.

conclusion

Key points of replay attack defense:

  • Record request identification and cache, verify when accepting request, reject replay, that isnonceStore in cache and reject the samenonce
  • The method of random number may cause too much cache, so it is necessary to filter with the timestamp. If the timestamp is not in the valid range, it is rejected.

Replay attack is a common and effective attack method, and its harm cannot be ignored. Although data correctness can be guaranteed at the business level, it still causes unnecessary overhead to the system. Filtering out replay requests at the gateway layer is a good choice.

If this article is helpful to you, please give a thumbs up (~ ▽ ~)”

Series of articles:

  • Open API Gateway Practice # 1 — Design an API gateway
  • Open API Gateway Practice ii – Replay attack and Defense
  • Open API Gateway Practice iii – Limiting traffic

Welcome to our official account:

[Copyright Notice]


This article was published on
Park Seo-kyung’s blog, allow non-commercial reprint, but reprint must retain the original author
PiaoRuiQingAnd links:
blog.piaoruiqing.comFor negotiation or cooperation on authorization, please contact:
[email protected].