首页 > 解决方案 > 在下面的程序中可以输入什么来访问数组?

问题描述

由于x没有真正验证并通过 scanf 接收,因此应该有可能被污染的数据可用于访问bytes.

代码(不是真正合乎逻辑地做任何有成效的事情):

void getMyBytes(){
    int x, byte;
    int bytes[20];
    scanf("%u %u", &x, &byte);
    bytes[x-1] = byte;
}

此代码的一个已知简单(丑陋)修复是:

void getMyBytes(){
    int x, byte;
    int bytes[20];
    scanf("%u %u", &x, &byte);
    if (x > sizeof(bytes)/sizeof(*bytes)) return;    --> validation fix
    bytes[x-1] = byte;
}

我可以在 scanf 中输入哪些输入以便我可以访问bytes

标签: c++exploit

解决方案


这取决于您的应用程序,但在访问您的内部成员时,您应该始终绑定检查外部输入。如何报告这取决于您。但是考虑使用std::vectororstd::array来帮助你。在您的示例中:

void getMyBytes(){
    int x, byte;
    std::array<int, 20> bytes; // Bad name btw, an int is very unlikely to be a byte.
    scanf("%u %u", &x, &byte); // scanf is not type safe. Consider using cin <<
    bytes.at(x-1) = byte; // Automatically bound checks for you and will throw an exception
                          // in the case that you are out of bounds. Very useful :)
}

std::array::at

返回对指定位置 pos 的元素的引用,并进行边界检查。如果 pos 不在容器的范围内,则抛出 std::out_of_range 类型的异常。

您可能会报告错误的其他方式包括:

  1. 调试中的硬死:assert(x >= 0 && x < bytes.size() && "I crashed here because you gave me bad input!")
  2. 向函数调用者报告错误:if (x < 0 || x > bytes.size()) { return false; }
  3. 抛出更多信息:if (x < 0) { throw my_special_underrun_exception; }if (x > bytes.size()) { throw my_special_overrun_exception; }

最后考虑访问CppCoreGuidelines以获取有关如何编写好的代码的大量提示。


推荐阅读