🔐 Ba kịch bản tấn công API phổ biến & giải pháp HMAC / Anti‑replay

Chủ đề: Parameter Tampering, Request Tampering, Replay Attack. Mục tiêu: hiểu cách tấn công, tác hại, và triển khai HMAC, Nonce/Timestamp, Idempotency.


1) Parameter Tampering / IDOR → Ký tham số URL bằng HMAC

Định nghĩa

Kẻ tấn công sửa tham số URL (query/path) để thay đổi hành vi hoặc truy cập dữ liệu không hợp lệ. Nếu API tin tưởng giá trị đó → lộ lọt dữ liệu/logic (IDOR).

Ví dụ tấn công

GET /orders?userId=1001   # hợp lệ
GET /orders?userId=1002   # attacker đổi ID

Giải pháp: HMAC ký tham số

  • Trả về URL có tham số đã ký và có hạn:
/product?id=123&price=1000&exp=1734261600&sig=nyMrcgGHxqtv-eL3...
  • exp: hết hạn; sig = HMAC_SHA256(canonical_params, SECRET)
  • Nguyên tắc: sort key → build chuỗi canonical → HMAC → server verify → sai/hết hạn ⇒ reject.

✅ Code demo (Java/Spring Boot) – ký & verify tham số

// Sig.java – tiện ích HMAC + canonical
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.util.*;
import java.util.stream.Collectors;
import java.util.Base64;

public class Sig {
    public static final String SECRET = "change-me-super-secret"; // đưa vào vault/KMS

    public static String hmacSha256(String data, String secret) {
        try {
            Mac mac = Mac.getInstance("HmacSHA256");
            mac.init(new SecretKeySpec(secret.getBytes(StandardCharsets.UTF_8), "HmacSHA256"));
            byte[] out = mac.doFinal(data.getBytes(StandardCharsets.UTF_8));
            return Base64.getUrlEncoder().withoutPadding().encodeToString(out);
        } catch (Exception e) { throw new RuntimeException(e); }
    }

    public static String canonicalize(Map<String, String> params) {
        return params.entrySet().stream()
                .filter(e -> e.getKey() != null && e.getValue() != null && !"sig".equals(e.getKey()))
                .sorted(Map.Entry.comparingByKey())
                .map(e -> e.getKey() + "=" + e.getValue())
                .collect(Collectors.joining("&"));
    }

    public static boolean ctEquals(String a, String b) {
        if (a == null || b == null || a.length() != b.length()) return false;
        int r = 0; for (int i=0;i<a.length();i++) r |= a.charAt(i) ^ b.charAt(i);
        return r == 0;
    }
}
// UrlSigningService.java – tạo URL đã ký
import java.time.Instant;
import java.util.*;

public class UrlSigningService {
    public String buildSignedProductUrl(String slug, String price, String color) {
        long exp = Instant.now().getEpochSecond() + 300; // 5 phút
        Map<String,String> p = new LinkedHashMap<>();
        p.put("id", slug);
        p.put("price", price);
        p.put("color", color); // tham số hiển thị
        p.put("exp", String.valueOf(exp));

        String data = Sig.canonicalize(p);
        String sig = Sig.hmacSha256(data, Sig.SECRET);
        return "/product?" + data + "&sig=" + sig;
    }
}
// ProductController.java – verify HMAC khi nhận request
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.time.Instant;
import java.util.*;

@RestController
public class ProductController {
    @GetMapping("/product")
    public ResponseEntity<?> getProduct(@RequestParam Map<String,String> params) {
        String sig = params.get("sig");
        String exp = params.get("exp");
        if (sig == null || exp == null) return ResponseEntity.status(400).body("missing sig/exp");
        // build canonical chỉ với các key có ý nghĩa
        Map<String,String> forSign = new HashMap<>();
        if (params.get("id") != null) forSign.put("id", params.get("id"));
        if (params.get("price") != null) forSign.put("price", params.get("price"));
        if (params.get("color") != null) forSign.put("color", params.get("color"));
        forSign.put("exp", exp);

        // check exp
        long now = Instant.now().getEpochSecond();
        if (now > Long.parseLong(exp)) return ResponseEntity.status(410).body("link expired");

        String data = Sig.canonicalize(forSign);
        String expected = Sig.hmacSha256(data, Sig.SECRET);
        if (!Sig.ctEquals(sig, expected)) return ResponseEntity.status(403).body("invalid signature");

        // TODO: load product, render theo color hợp lệ, price lấy từ DB, không tin client
        return ResponseEntity.ok("OK – signature valid");
    }
}
# cURL test – đổi price sẽ làm sig sai
curl 'http://localhost:8080/product?id=iphone-15&price=1000&color=blue&exp=1734261600&sig=...' \
  -i

2) Request Tampering / Payload Manipulation → Ký toàn request (body hash)

Định nghĩa

Kẻ tấn công sửa body của POST/PUT/PATCH (ví dụ amount, price, role).

Giải pháp: HMAC request signing (server ↔ client có shared secret)

  • Ký method + path + query chuẩn hóa + content-type + SHA‑256(body) + timestamp + nonce.
  • Gửi kèm header: Authorization: HMAC <apiKey>:<signature>, X-Date, X-Nonce.

✅ Code demo – Filter verify chữ ký HMAC cho POST

// HmacAuthFilter.java – verify HMAC cho mọi request nhạy cảm
import org.springframework.web.filter.OncePerRequestFilter;
import javax.servlet.*; import javax.servlet.http.*; import java.io.*; import java.time.*; import java.util.*;

public class HmacAuthFilter extends OncePerRequestFilter {
    private final KeyService keyService;      // apiKey -> secret
    private final NonceStore nonceStore;      // Redis/memory – chống replay

    public HmacAuthFilter(KeyService keyService, NonceStore nonceStore) {
        this.keyService = keyService; this.nonceStore = nonceStore;
    }

    @Override protected void doFilterInternal(HttpServletRequest req, HttpServletResponse res, FilterChain chain)
            throws IOException, ServletException {
        String auth = req.getHeader("Authorization");
        String xDate = req.getHeader("X-Date");
        String xNonce = req.getHeader("X-Nonce");
        if (auth == null || xDate == null || xNonce == null) { res.sendError(401); return; }

        String[] p = auth.split(" ", 2); if (p.length!=2 || !"HMAC".equals(p[0])) { res.sendError(401); return; }
        String[] cred = p[1].split(":", 2); if (cred.length!=2) { res.sendError(401); return; }
        String apiKey = cred[0], sig = cred[1];

        long now = Instant.now().getEpochSecond();
        long ts = parseEpochOrIso(xDate);
        if (Math.abs(now - ts) > 300) { res.sendError(401, "clock skew"); return; }
        if (!nonceStore.tryUse(apiKey, xNonce, 300)) { res.sendError(401, "replay"); return; }

        String method = req.getMethod().toUpperCase();
        String path = req.getRequestURI();
        String qs = canonicalQuery(req.getQueryString());
        String ctype = Optional.ofNullable(req.getContentType()).orElse("");

        byte[] body = req.getInputStream().readAllBytes();
        String bodySha256 = sha256Hex(body);

        String canonical = method+"\n"+path+"\n"+qs+"\n"
                +"content-type:"+ctype+"\n"
                +"x-date:"+xDate+"\n"
                +"x-nonce:"+xNonce+"\n"
                +"sha256="+bodySha256;

        String secret = keyService.getSecret(apiKey);
        String expected = Sig.hmacSha256(canonical, secret);
        if (!Sig.ctEquals(sig, expected)) { res.sendError(401, "bad signature"); return; }

        // Pass xuống controller
        chain.doFilter(new CachedBodyRequestWrapper(req, body), res);
    }

    // Helpers (tối giản demo)
    private String canonicalQuery(String raw) { return raw==null||raw.isEmpty()?"":Arrays.stream(raw.split("&"))
        .map(s->s.split("=",2)).sorted(Comparator.comparing(a->a[0]))
        .map(a->a[0]+"="+(a.length>1?a[1]:""))
        .reduce((a,b)->a+"&"+b).orElse(""); }
    private String sha256Hex(byte[] b){ try{
        java.security.MessageDigest md=java.security.MessageDigest.getInstance("SHA-256");
        byte[] d=md.digest(b); StringBuilder sb=new StringBuilder();
        for(byte x:d) sb.append(String.format("%02x",x)); return sb.toString(); }catch(Exception e){throw new RuntimeException(e);} }
    private long parseEpochOrIso(String s){ try{ return Long.parseLong(s);}catch(Exception e){ return Instant.parse(s).getEpochSecond(); }}
}
// CachedBodyRequestWrapper.java – cho phép đọc body nhiều lần sau khi verify
import javax.servlet.ReadListener; import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletRequestWrapper;
import java.io.*;

public class CachedBodyRequestWrapper extends HttpServletRequestWrapper {
    private final byte[] body;
    public CachedBodyRequestWrapper(HttpServletRequest request, byte[] body) { super(request); this.body = body; }
    @Override public ServletInputStream getInputStream() { return new ServletInputStream(){
        private int idx=0; @Override public boolean isFinished(){ return idx>=body.length; }
        @Override public boolean isReady(){ return true; }
        @Override public void setReadListener(ReadListener readListener){}
        @Override public int read(){ return idx<body.length ? body[idx++] & 0xff : -1; }
    }; }
}
// Interfaces tối giản – tự hiện thực bằng Redis/KV thật trong dự án
public interface KeyService { String getSecret(String apiKey); }
public interface NonceStore { boolean tryUse(String apiKey, String nonce, int ttlSeconds); }
# cURL mẫu – client đã ký sẵn (minh hoạ)
curl -X POST 'http://localhost:8080/payments' \
  -H 'Content-Type: application/json' \
  -H 'X-Date: 2025-08-25T10:00:00Z' \
  -H 'X-Nonce: 8f1d6f9b-6a4c-4b1a-8f2c-0a9d2a0a1234' \
  -H 'Authorization: HMAC myKey:BASE64URL_SIGNATURE' \
  -d '{"orderId":"12345","amount":500000}'

Lưu ý: Không nhúng secret ở web browser. HMAC request signing chỉ dùng cho server‑to‑server hoặc mobile app có secure storage.


3) Replay Attack / Brute Force → Nonce + Timestamp + Idempotency + Rate limit

Định nghĩa

  • Replay: gửi lại request hợp lệ để lặp giao dịch.
  • Brute force/DoS: spam request để quá tải/đo giá trị hợp lệ.

Giải pháp chính

  1. Nonce + Timestamp (Anti‑replay) – đã có trong filter ở trên.
  2. Idempotency‑Key cho POST tạo tài nguyên/thanh toán: cùng key ⇒ cùng kết quả.
  3. Rate limiting / Quota theo IP/user/API key.

✅ Code demo – Idempotency cho POST (Redis giả lập)

// IdempotencyFilter.java – đảm bảo 1 key = 1 kết quả
import org.springframework.web.filter.OncePerRequestFilter;
import javax.servlet.*; import javax.servlet.http.*; import java.io.*; import java.util.*;

public class IdempotencyFilter extends OncePerRequestFilter {
    private final IdemStore store; // Redis/KV thực tế
    public IdempotencyFilter(IdemStore store){ this.store = store; }

    @Override protected void doFilterInternal(HttpServletRequest req, HttpServletResponse res, FilterChain chain)
            throws IOException, ServletException {
        if (!"POST".equalsIgnoreCase(req.getMethod())) { chain.doFilter(req,res); return; }
        String key = req.getHeader("Idempotency-Key");
        if (key == null || key.isEmpty()) { res.sendError(400, "Missing Idempotency-Key"); return; }

        // Nếu đã có kết quả thì trả luôn (cache theo key)
        byte[] cached = store.get("idem:res:"+key);
        if (cached != null) {
            res.setHeader("Idempotency-Key", key);
            res.setHeader("Idempotency-Replay", "true");
            res.setStatus(200);
            res.getOutputStream().write(cached);
            return;
        }

        // Khoá ngắn để chống song song
        if (!store.lock("idem:lock:"+key, 60)) { res.sendError(425, "Too Early"); return; }
        try {
            // Capture response body
            ByteArrayOutputStream buffer = new ByteArrayOutputStream();
            HttpServletResponseWrapper wrap = new HttpServletResponseWrapper(res) {
                @Override public ServletOutputStream getOutputStream() { return new ServletOutputStream(){
                    @Override public boolean isReady(){ return true; }
                    @Override public void setWriteListener(WriteListener writeListener){}
                    @Override public void write(int b) throws IOException { buffer.write(b); }
                }; }
            };
            chain.doFilter(req, wrap);
            byte[] body = buffer.toByteArray();
            store.set("idem:res:"+key, body, 24*3600);
            res.setHeader("Idempotency-Key", key);
            res.setHeader("Idempotency-Replay", "false");
            res.getOutputStream().write(body);
        } finally {
            store.unlock("idem:lock:"+key);
        }
    }
}
// IdemStore.java – interface tối giản (triển khai bằng Redis)
public interface IdemStore {
    byte[] get(String key);
    void set(String key, byte[] value, int ttlSeconds);
    boolean lock(String key, int ttlSeconds);
    void unlock(String key);
}
# cURL dùng Idempotency-Key – lần 2 sẽ nhận lại response cũ
curl -X POST 'http://localhost:8080/payments' \
  -H 'Content-Type: application/json' \
  -H 'Idempotency-Key: c0b5e2e8-7b1b-4c0a-9f5e-111122223333' \
  -d '{"orderId":"12345","amount":500000}' -i

✅ Code demo – Rate limit đơn giản (Bucket4j)

// RateLimitConfig.java – giới hạn theo API key/IP
import io.github.bucket4j.*;
import org.springframework.context.annotation.*;
import javax.servlet.*; import javax.servlet.http.*; import java.io.IOException; import java.time.Duration; import java.util.*; import java.util.concurrent.ConcurrentHashMap;

@Configuration
public class RateLimitConfig {
    private final Map<String, Bucket> buckets = new ConcurrentHashMap<>();
    private Bucket resolve(String key) {
        return buckets.computeIfAbsent(key, k -> Bucket4j.builder()
            .addLimit(Bandwidth.classic(100, Refill.greedy(100, Duration.ofMinutes(1))))
            .addLimit(Bandwidth.classic(10, Refill.greedy(10, Duration.ofSeconds(1))))
            .build());
    }

    @Bean public Filter rateLimitFilter() {
        return new Filter() {
            @Override public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
                HttpServletRequest r = (HttpServletRequest) req; HttpServletResponse s = (HttpServletResponse) res;
                String key = Optional.ofNullable(r.getHeader("X-Api-Key")).orElse(r.getRemoteAddr());
                if (resolve(key).tryConsume(1)) chain.doFilter(req, res);
                else { s.setStatus(429); s.setHeader("Retry-After", "1"); }
            }
        }; }
}

4) Bảng so sánh & kết luận nhanh

CaseTên tấn côngVí dụTác hạiGiải pháp chính
1Parameter Tampering / IDOR/orders?userId=1002Lộ dữ liệu, gian lậnHMAC params, AuthZ, whitelist
2Request Tamperingamount=1000 thay vì 500000Gian lận, sai dữ liệuHMAC body, schema validation, business rule
3Replay AttackGửi lại cURL 10 lầnDouble charge, DoSNonce+Timestamp, Idempotency‑Key, Rate limit

3 nguyên tắc vàng:

  1. Xác thực/ủy quyền chặt chẽ.
  2. Toàn vẹn dữ liệu (HMAC/JWT, body hash, signed params).
  3. Giới hạn & kiểm soát (anti‑replay, idempotency, rate limit).

Áp dụng đồng bộ các kỹ thuật trên sẽ tăng đáng kể độ an toàn cho API và giảm thiểu nguy cơ bị khai thác.