Skip to content

堆越界的影响分析 #28

@lfeng14

Description

@lfeng14
  • 小例子仅检测到写溢出,并没有覆盖相邻对象;试试具体工程是否有覆盖情况;使用方法:保持原来编译器,加上选项-fsanitize=address就行

  • 例子

    cat  > multi_class_victim.cpp << EOF
    #include <iostream>
    #include <cstring>
    
    class Config {
    public:
        char name[16];
        Config() { std::strcpy(name, "SystemConfig"); }
    };
    
    class SecretData {
    public:
        int password;
        SecretData() { password = 123456; }
    };
    
    int main() {
        // 连续分配两个不同类的对象
        Config* cfg = new Config();
        SecretData* secret = new SecretData(); // 它是潜在的“受害者”
    
        std::cout << "Config Address: " << (void*)cfg << std::endl;
        std::cout << "Secret Address: " << (void*)secret << std::endl;
    
        // 故意越界:Config 只有 16 字节,我们写到第 24 字节(通常会踩到 SecretData)
        std::cout << "\n--- Triggering Overflow ---" << std::endl;
        cfg->name[24] = 'X'; 
    
        delete cfg;
        delete secret;
        return 0;
    }
    EOF
    
  • 命令(建议使用原来编译器构建)

    clang++ -O0 -g -fsanitize=address multi_class_victim.cpp -o asan_test
    g++ -O0 -g -fsanitize=address multi_class_victim.cpp -o asan_test
    
  • 输出

    Image
  1	#include <iostream>
  2	#include <cstring>
  3	
  4	class Config {
  5	public:
  6	    char name[16];
  7	    Config() { std::strcpy(name, "SystemConfig"); }
  8	};
  9	
 10	class SecretData {
 11	public:
 12	    int password;
 13	    SecretData() { password = 123456; }
 14	};
 15	
 16	int main() {
 17	    // 连续分配两个不同类的对象
 18	    Config* cfg = new Config();
 19	    SecretData* secret = new SecretData(); //  可能受影响的类
 20	
 21	    std::cout << "Config Address: " << (void*)cfg << std::endl;
 22	    std::cout << "Secret Address: " << (void*)secret << std::endl;
 23	
 24	    // 故意越界:Config 只有 16 字节,我们写到第 24 字节(通常会踩到 SecretData)
 25	    std::cout << "\n--- Triggering Overflow ---" << std::endl;
 26	    cfg->name[24] = 'X'; 
 27	
 28	    delete cfg;
 29	    delete secret;
 30	    return 0;
 31	}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions