如何防止从系统目录中包含文件

How do I prevent an include of files out of system directories?

本文关键字:包含 文件 系统目录 何防止      更新时间:2023-10-16

出于安全原因,我必须阻止系统目录中任何文件的#include。是否有任何限制可以阻止#include<...>#include"..."包含不安全的文件,如#include </dev/tty>#include "/dev/random" ?

我已经阅读了C预处理器文档的头文件章节以及类似的问题,我如何防止引用的包含搜索当前源文件的目录?但我找不到合适的方法。

由于-I-命令已经过时,并且没有其他方法可以完成相同的功能,我可以使用jailkit作为低权限用户来编译代码吗?还是有其他方法来保证编译过程的安全性?

godbolt.org通过禁止在 #includes中使用绝对路径和相对路径来解决类似的问题:

输入:

#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
相关文章: