【问题标题】:how to write a uint64_t to a char* buffer in C如何将 uint64_t 写入 C 中的 char* 缓冲区
【发布时间】:2021-11-02 03:05:56
【问题描述】:

所以我尝试将 uint64_t 返回地址写入缓冲区,然后验证正确的返回地址是否已写入正确的位置。这是我的代码。

  uint64_t new_ret = ret - 8 - 32 - 32 - 1001 + (ret_buffer_offset + sizeof(shellcode));
  printf("new_ret :%lu\n", new_ret);
  snprintf(&buffer[ret_buffer_offset], 8, "%s", new_ret);

  // debug code 
    char buffer_debug[10];
    uint64_t* buffer_uint = (uint64_t*)buffer_debug;
    bzero(buffer_debug, 10);
    strncpy(buffer_debug, &buffer[ret_buffer_offset], 8);
    uint64_t ret_debug = *buffer_uint;
    printf("ret debug: %lu\n", ret_debug); 

两个 printf 应该输出相同的东西,但底部的 printf 输出一个非常不同的数字。我不确定我写入缓冲区的方式是否错误,或者我获取值的方式是否错误。这里有什么问题?

谢谢

【问题讨论】:

  • 只用memcpy?
  • @tstanisl lmao 谢谢,我不敢相信我忘记了 memcpy。数字仍然不匹配,但我现在非常确信问题出在我的调试代码上

标签: c security buffer buffer-overflow shellcode


【解决方案1】:
snprintf(&buffer[ret_buffer_offset], 8, "%s", new_ret);

buffer 现在包含原始值的字符串表示(或至少字符串表示的前 8 个字节)。然后,您的代码会获取该字符串的前 8 个字节,并将该二进制序列解释为好像它是 uint64_t。在调试器中单步执行这段代码,您将确切地看到值发生变化的地方。

我不确定这段代码到底想做什么,但它似乎做了比必要更多的复制和转换。如果你有一个指向你想要值去的地方的指针,你应该可以做memcpy(ptr, &new_ret, sizeof(new_ret)),或者甚至可能*(uint64_t*)ptr = new_ret,如果你的平台允许潜在的错位写入。要打印出调试值,您可以使用printf("%"PRIu64, *(uint64_t*)ptr)

【讨论】:

    【解决方案2】:

    我喜欢使用union,但如果你将char 指针(char*)指向uint64_t 的地址,它就可以工作。 使用指针将是:

    uint64_t new_ret = ret - 8 - 32 - 32 - 1001 + (ret_buffer_offset + sizeof(shellcode));
    buffer = (char*) &new_ret;
    

    测试下面的代码使用联合和指针:

    #include <stdio.h>
    #include <stdint.h>
    
    int main(){
        union {
            uint64_t u64;
            char str[8];
        } handler;
        handler.u64 = 65;
        printf("Using union:\n");
        printf(" uint64: %ld\n", handler.u64);
        printf(" char*:  %s\n",  handler.str);
    
        uint64_t u64 = 65;
        char *str = (char*)&u64;
        printf("Using pointer:\n");
        printf(" uint64: %ld\n", u64);
        printf(" char*:  %s\n",  str);
    
        return 0;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-09-14
      • 2017-01-05
      • 1970-01-01
      • 1970-01-01
      • 2018-12-31
      • 2014-06-26
      • 2012-05-27
      • 2012-05-08
      相关资源
      最近更新 更多