如何防止从系统目录中包含文件
How do I prevent an include of files out of system directories?
出于安全原因,我必须阻止系统目录中任何文件的#include
。是否有任何限制可以阻止#include<...>
和#include"..."
包含不安全的文件,如#include </dev/tty>
或#include "/dev/random"
?
我已经阅读了C预处理器文档的头文件章节以及类似的问题,我如何防止引用的包含搜索当前源文件的目录?但我找不到合适的方法。
由于-I-
命令已经过时,并且没有其他方法可以完成相同的功能,我可以使用jailkit作为低权限用户来编译代码吗?还是有其他方法来保证编译过程的安全性?
godbolt.org通过禁止在 #include
s中使用绝对路径和相对路径来解决类似的问题:
#include "/etc/passwd"
输出:<stdin>:1:1: no absolute or relative includes please
Compilation failed
这可以通过在调用编译器之前对源代码运行一个简单的检查器来实现。检查器只需要搜索#include
指令,并检查路径是否违反了这些限制。这样一个脚本的草稿版本(可用于单个源文件)如下:
check_includes :
#!/bin/bash
if (( $# != 1 ))
then
echo "Usage: $(basename "$0") source_file"
exit 1
fi
join_lines()
{
sed '/\$/ {N;s/\n//;s/^/n/;D}' "$1"
}
absolute_includes()
{
join_lines "$1"|grep '^s*#s*includes*["<]s*/'
}
relative_includes()
{
join_lines "$1"|grep '^s*#s*include'|fgrep '../'
}
includes_via_defines()
{
join_lines "$1"|grep '^s*#s*includes*[^"< t]'
}
show_and_count()
{
tee /dev/stderr|wc -l
}
exit_status=0
if (( 0 != $(absolute_includes "$1"|show_and_count) ))
then
echo 1>&2 "ERROR: $1 contains absolute includes"
exit_status=1
fi
if (( 0 != $(relative_includes "$1"|show_and_count) ))
then
echo 1>&2 "ERROR: $1 contains relative includes"
exit_status=1
fi
if (( 0 != $(includes_via_defines "$1"|show_and_count) ))
then
echo 1>&2 "ERROR: $1 contains includes via defines"
exit_status=1
fi
exit $exit_status
假设可以编译输入文件而没有错误,该脚本识别包含绝对或相对路径的#include
。它还检测通过如下宏完成的包含(这可能被滥用来绕过路径检查):
#define HEADER "/etc/password"
#include HEADER
相关文章:
- vcruntime.h 从 Windows 包含文件夹中丢失?
- 禁止显示有关包含文件中 #pragma 包的警告
- 无法打开包含文件:在 vs2017 上'QtWidgets/qtwidgetsglobal.h'
- 包含文件 <sched_yield.h>在我的 RHEL 5 上找不到
- 尝试使用 MSVC 从源代码构建 qt 创建器:无法打开包含文件:"stddef.h":没有这样的文件或目录
- 无法打开包含文件'Graphics.hpp'没有这样的文件或目录,Visual Studio的其他包含不起作用
- 为什么 C++ 编译器在"c:program filesgnu emacsinclude"中查找包含文件?
- 包含文件中的 Typdef "未在此范围内声明"
- 错误: C1083: 无法打开包含文件:"boost/asio.hpp": 没有此类文件或目录
- SFML c ++ 当包含文件内游戏中发生事件时,如何使用铃声函数为我的游戏创建声音类?
- 在Windows上设置CMake和vcpkg时出错"无法打开包含文件"
- 致命错误 C1083:无法打开包含文件:"GL/glew.h":没有此类文件或目录
- Qt自动生成的.rc文件无法打开包含文件'windows.h'
- Visual Studio 停止识别任何包含文件
- 无法打开包含文件:"签证.h"
- 如何检查每个头文件是否包含必需的包含文件?
- Protobuf:无法在 message.pb.h 文件中打开包含文件 common.h
- extern 关键字在包含文件头文件C++
- 错误:无法打开包含文件:"MQTTAsync.h":没有此类文件或目录
- #include "date.h" 创建错误 E1696 无法打开源文件"date.h",也无法打开包含文件:没有这样的文件或目录