Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <stdint.h>
- #include <fcntl.h>
- #include <unistd.h>
- #include <sys/ioctl.h>
- #include <asm-x86/msr.h>
- #define MSR_ADDR 0xC0011002
- // Function to read an MSR
- uint64_t read_msr(int fd, uint32_t msr) {
- uint64_t value;
- if (pread(fd, &value, sizeof(value), msr) != sizeof(value)) {
- perror("Error reading MSR");
- return -1;
- }
- return value;
- }
- // Function to write an MSR
- void write_msr(int fd, uint32_t msr, uint64_t value) {
- if (pwrite(fd, &value, sizeof(value), msr) != sizeof(value)) {
- perror("Error writing MSR");
- }
- }
- // Function to modify bit 18 of MSR 0xC0011002
- void set_msr_bit_18(int fd, int set) {
- uint64_t msr_value = read_msr(fd, MSR_ADDR);
- if (msr_value == (uint64_t)-1) {
- return; // Error reading MSR
- }
- if (set) {
- // Set bit 18
- msr_value |= (1ULL << 18);
- } else {
- // Clear bit 18
- msr_value &= ~(1ULL << 18);
- }
- write_msr(fd, MSR_ADDR, msr_value);
- }
- int supports_rdseed() {
- uint32_t eax, ebx, ecx, edx;
- __asm__ (
- "cpuid"
- : "=a" (eax), "=b" (ebx), "=c" (ecx), "=d" (edx)
- : "a" (0x7), "c" (0)
- );
- return ebx; // Check bit 18 (RDSEED flag)
- }
- uint32_t rdseed() {
- uint32_t result;
- // Inline assembly to use RDSEED instruction
- __asm__ __volatile__ (
- "rdseed %0" // RDSEED instruction, stores result in result
- : "=r" (result) // Output operand
- : // No input operands
- : "memory" // Clobbered register
- );
- return result;
- }
- int main()
- {
- //you need to disable each core or limit program to run at one core
- int msr_fd = open("/dev/cpu/0/msr", O_RDWR);
- if (msr_fd == -1) {
- perror("Error opening msr");
- return 1;
- }
- printf("RDSEED flag 0x%08x %u\n", supports_rdseed() , (supports_rdseed() >> 18) & 1 );
- // set_msr_bit_18(msr_fd, 1);
- printf("RDSEED flag 0x%08x %u\n", supports_rdseed() , (supports_rdseed() >> 18) & 1 );
- set_msr_bit_18(msr_fd, 0);
- printf("RDSEED flag 0x%08x %u\n", supports_rdseed() , (supports_rdseed() >> 18) & 1 );
- uint32_t random_value = rdseed();
- printf("Random number: %u\n", random_value);
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment