Fading Coder

One Final Commit for the Last Sprint

Home > Tech > Content

Secure API Design: Preventing Data Tampering and Replay Attacks

Tech May 18 9

Overview

Background

The motivation behind sharing best practices for API security stems from my professional experience, where I have been responsible for implementing such safeguards. Additionally, many backend developers lack deep understanding of these security aspects or are unsure how to achieve adequate protection. This write-up aims to offer practical insights and encourage collaborative learning.

It's important to note that this perspective reflects personal experience and may not represent universally accepted standards. Security measures should always be evaluated critically and customized based on specific use cases.

Scope

This section addresses HTTP API security design, covering aspects like eavesdropping prevention, data integrity, replay attack mitigation, secure key exchange, secure key storage, and sensitive data handling. It is intended for backend engineers, QA professionals, and security practitioners involved in API development.

Data Integrity Protection

Digital Signatures

To prevent data manipulation, clients can generate a digital signature using algorithms such as MD5. For instance, parameters from the request can be concatenated and hashed to produce an MD5 value, which is then sent to the server for validation.

However, this approach has limitations. If attackers know the algorithm, they might still forge signatures. To enhance robustness, asymmetric cryptographic methods like RSA or SM2 are recommended. These systems utilize a private key for signing and a public key for verification, ensuring that even if the public key is exposed, unauthorized modification remains infeasible.

In practice, the client signs requests using its private key, while the server stores the corresponding public key for validation. Similarly, servers can sign responses using their private keys, enabling bidirectional integrity checks.

Common Algorithms

Popular choices include RSA (1024/2048 bits), SM2, and elliptic curve cryptography (ECC). While RSA 1024 was once common, modern implementations typically favor 2048-bit keys or longer. In China, SM2 is widely adopted due to its compact signature size (64 bytes) compared to RSA, which scales with key length, increasing cmoputational overhead.

Signature Construction

GET Requests

For GET requests, parameters should be sorted alphabetically before concatenation:

# Example URL
http://127.0.0.1:8080/testGet?p=testp&ab=123&x=456

# Sorted and concatenated string
ab=123&p=testp&x=456
POST Form Data

Similar to GET, form data parameters are sorted and concatenated:

# Request body
p=test1&ab=123&x=456

# After sorting
ab=123&p=test1&x=456
POST Body

For JSON payloads, the raw body content is included as a parameter named entity:

{
  "pInt": 1,
  "pBoolean": false,
  "pString": "ssss"
}

Resulting in:

entity={"pInt": 1,"pBoolean": false,"pString": "ssss"}
Handling Edge Cases

Empty parameters pose challenges. To mitigate this, include the endpoint path in the signed data:

ab=123&p=testp&x=456&path=/testGet

This ensures that identical parameters across different endpoints cannot be reused mailciously.

Signature Placement

Signatures can be placed in headers or as part of common parameters, depending on implementation needs.

Algorithm Considerations

Key points about SM2:

  1. Signing requires the private key; verification uses the public key.
  2. Verification involves more complex operations than signing.
  3. For performance, store both keys on the server side.
  4. The userid parameter defaults to 1234567812345678, but can be customized for enhanced security.
  5. Random number generation is critical for security—ensure proper entropy sources.

Clustered Deployment

To support horizontal scaling, caching public keys in memory (e.g., Redis) helps avoid frequent database queries.

Implementation Tips

  1. Apply encodeURI when constructing signed strings for GET parameters.
  2. For POST requests, intercept and reprocess InputStreams during signature validation.
  3. Consider separating key management services for improved availability.
  4. Maintain consistent data types between frontend and backend during encryption processes.

Fallback Mechanism

In case Redis fails, pre-signed certificates can be used. These contain user identifiers, validity periods, and public keys signed by the server. Upon failure, clients send the certificate along with the request for validation.

This mechanism increases traffic and server load but provides fallback capability.

Replay Attack Mitigation

Even with digital signatures, repeated requests with identical parameters remain a threat. To counter this, timestamps are added to each request.

Timestamp-Based Validation

Add a timestamp header (X-TimeStamp) to the request:

X-TimeStamp: 1680503150

Include it in the signature data:

ab=123&p=testp&x=456&path=/testGet&timestamp=1680503150

Requests outside a configured window (e.g., 3 minutes) are rejected.

Additional Measures

While timestamps help, they don't fully prevent replays within valid windows. Combining them with nonces enhances security.

Nonce-Based Protection

Each request includes a unique nonce (X-Nonce) generated by the client:

X-Nonce: wX5krzyVHuaYS8Ta

The server validates uniqueness before processing:

ab=123&p=testp&x=456&path=/testGet&timestamp=1680503150&nonce=wX5krzyVHuaYS8Ta

If a duplicate nonce is detected, the request is discarded.

Important Notes

  • When timeouts occur, generate new nonces to prevent rejection.
  • Set expiration times for nonces aligned with timestamp validity.
  • Isolate nonce storage for high availability.

Learning Cybersecurity

There are three primary paths to learn cybersecurity:

  1. Formal Education: Enroll in computer science or cybersecurity programs covering topics like network protocols, cryptography, and penetration testing.
  2. Self-Study: Use online resources, tutorials, and community engagement to build foundational knowledge.
  3. Training Programs: Attend structured courses offered by institutions or companies.

Learning Path

Phase 1: Fundamentals (4–6 weeks)

Focus on core concepts such as networking, operating systems, and programming basics.

Phase 2: Web Penetration Testing (1–2 weeks)

Study vulnerabilities like SQL injection, XSS, CSRF, and file upload flaws. Practice with tools like Burp Suite, Nmap, and SQLMap.

Phase 3: Practical Application (6 weeks)

Engage in hands-on labs using vulnerable applications like DVWA, SQLi-labs, and bWAPP. Learn manual exploitation techniques and bypass methods.

Phase 4: Advanced Topics (Ongoing)

Deep dive into privilege escalation, post-exploitation, and advanced defensive strategies.

Related Articles

Understanding Strong and Weak References in Java

Strong References Strong reference are the most prevalent type of object referencing in Java. When an object has a strong reference pointing to it, the garbage collector will not reclaim its memory. F...

Comprehensive Guide to SSTI Explained with Payload Bypass Techniques

Introduction Server-Side Template Injection (SSTI) is a vulnerability in web applications where user input is improper handled within the template engine and executed on the server. This exploit can r...

Implement Image Upload Functionality for Django Integrated TinyMCE Editor

Django’s Admin panel is highly user-friendly, and pairing it with TinyMCE, an effective rich text editor, simplifies content management significantly. Combining the two is particular useful for bloggi...

Leave a Comment

Anonymous

◎Feel free to join the discussion and share your thoughts.