> For the complete documentation index, see [llms.txt](https://alham-rizvi.gitbook.io/alhamrizvi/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://alham-rizvi.gitbook.io/alhamrizvi/cryptography/hashing/43.-timing-attack-mac.md).

# 43. Timing Attack on MAC

## What is a Timing Attack?

A **timing attack** is a side-channel attack that exploits the time difference in operations to leak secret information.

For MAC verification, if comparison stops at the **first mismatched byte**, an attacker can guess the MAC byte-by-byte based on response time.

## Vulnerable Code Example

```python
# ❌ VULNERABLE — early exit on first mismatch
def verify(mac1, mac2):
    return mac1 == mac2   # Python str/bytes == is NOT constant-time
```

## Secure Code Example

```python
import hmac

# ✅ SECURE — constant-time comparison
def verify(mac1, mac2):
    return hmac.compare_digest(mac1, mac2)
```

## How the Attack Works

1. Send request with MAC = `00 00 00 ... 00`
2. Measure response time
3. Try `01 00 00 ... 00`, `02 00 00 ... 00`, etc.
4. When first byte is correct → response takes slightly longer
5. Repeat for each byte position

## CTF Exploitation Script (Skeleton)

```python
import requests
import time
import statistics

TARGET = "http://challenge.ctf/verify"
KNOWN = []

for pos in range(32):  # 32 bytes for SHA-256 MAC
    timings = {}
    for byte_val in range(256):
        candidate = KNOWN + [byte_val] + [0] * (31 - pos)
        mac = bytes(candidate).hex()
        times = []
        for _ in range(10):  # average over multiple requests
            start = time.perf_counter()
            requests.post(TARGET, json={"mac": mac})
            elapsed = time.perf_counter() - start
            times.append(elapsed)
        timings[byte_val] = statistics.mean(times)
    best = max(timings, key=timings.get)
    KNOWN.append(best)
    print(f"Byte {pos}: {best:02x}")

print("MAC:", bytes(KNOWN).hex())
```

## Notes

* Timing attacks are **statistical** — require many samples to be reliable
* Network jitter makes remote timing attacks harder (but not impossible)
* Tools like `dudect` analyze timing distributions statistically
* Often combined with oracle attacks in CTF challenges


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter, and the optional `goal` query parameter:

```
GET https://alham-rizvi.gitbook.io/alhamrizvi/cryptography/hashing/43.-timing-attack-mac.md?ask=<question>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
