如何复制函数指令并存入缓冲区?

问题描述 投票:0回答:1

这段代码为什么不直接将

func
的汇编指令存入缓冲区呢?缓冲区的值是垃圾并且不会改变。

#include <stdio.h> 
#include <stdlib.h> 
#include <string.h> 
#include <unistd.h> 
char buffer[1000];
uint64_t* addr; 

void func() { 
// here should be what the function really do
    addr = (uint64_t*)&func; 
    memcpy(buffer, &addr, 1000);  // im expecting that the instructions of func will be stored in the buffer 
    strcpy(secret, hash(secret, buffer)); // secret is previous hash of the function before it so i can make  hash chain to verify the control flow integrity  

    // also the 1000 is not the actual size for the function, i just used it here for clarification 
} 
c security control-flow controlflowguard
1个回答
0
投票
  • 不保证
    &func
    会引用您可以读取的内存。
  • 无法保证
    memcpy
    会在您的平台上将此引用用作函数指针 而不是 数据指针。

但是如果它有效,那么您的代码将复制变量地址及其后面的下一个字节(并且它会调用未定义的行为)

void func() { 
    memcpy(buffer, (void *)&func, 1000); 
    /* ... */
}

此代码也调用了 UB,但它可能在某些平台上工作。

© www.soinside.com 2019 - 2024. All rights reserved.