转载自:http://www.jackieathome.net/archives/796.html
前言
今天在学习编译器堆栈保护技术时,突然发现gcc的安全编译选项我还从来没去了解过
发现一篇写的不错的帖子,进行转载保存
以CMake为例,给出安全编译选项的定义
关闭RPATH特性
set(CMAKE_SKIP_RPATH TRUE)
开启栈保护
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -fstack-protector-strong")
或者
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -fstack-protector-all")
开启GOT表保护
set(CMAKE_SHARED_LINKER_FLAGS "${CMAKE_SHARED_LINKER_FLAGS} -Wl,-z,relro,-z,now")
set(CMAKE_EXECUTABLE_LINKER_FLAGS "${CMAKE_EXECUTABLE_LINKER_FLAGS} -Wl,-z,relro,-z,now")
开启栈不可执行
set(CMAKE_SHARED_LINKER_FLAGS "${CMAKE_SHARED_LINKER_FLAGS} -Wl,-z,noexecstack")
set(CMAKE_EXECUTABLE_LINKER_FLAGS "${CMAKE_EXECUTABLE_LINKER_FLAGS} -Wl,-z,noexecstack")
开启地址无关
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -fpic")
或者
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -fPIC")
随机化
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -fpie")
set(CMAKE_SHARED_LINKER_FLAGS "${CMAKE_SHARED_LINKER_FLAGS} -pie")
set(CMAKE_EXECUTABLE_LINKER_FLAGS "${CMAKE_EXECUTABLE_LINKER_FLAGS} -pie")
或者
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -fPIE")
set(CMAKE_SHARED_LINKER_FLAGS "${CMAKE_SHARED_LINKER_FLAGS} -pie")
set(CMAKE_EXECUTABLE_LINKER_FLAGS "${CMAKE_EXECUTABLE_LINKER_FLAGS} -pie")
隐藏暴露的符号
set(CMAKE_SHARED_LINKER_FLAGS "${CMAKE_SHARED_LINKER_FLAGS} -fvisibility=hidden")
set(CMAKE_EXECUTABLE_LINKER_FLAGS "${CMAKE_EXECUTABLE_LINKER_FLAGS} -fvisibility=hidden")
set(CMAKE_SHARED_LINKER_FLAGS "${CMAKE_SHARED_LINKER_FLAGS} -fvisibility-inlines-hidden")
set(CMAKE_EXECUTABLE_LINKER_FLAGS "${CMAKE_EXECUTABLE_LINKER_FLAGS} -fvisibility-inlines-hidden")
删除调试符号
对于Linux环境下部署应用,建议不使用本选项,否则会对测试、生产环境的问题定位产生影响
set(CMAKE_SHARED_LINKER_FLAGS "${CMAKE_SHARED_LINKER_FLAGS} -s")
set(CMAKE_EXECUTABLE_LINKER_FLAGS "${CMAKE_EXECUTABLE_LINKER_FLAGS} -s")
开启整数溢出检查
set(CMAKE_CXX_FLAGS_DEBUG "${CMAKE_CXX_FLAGS} -ftrapv")
开启栈检查
set(CMAKE_CXX_FLAGS_DEBUG "${CMAKE_CXX_FLAGS} -fstack-check")
上述选项对于Clang一样可用