1

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

我已阅读Docs of C Preprocessor的头文件章节以及类似的问题How do I prevent aquoted include search the directory of the current source file? 但找不到合适的方法。

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

4

1 回答 1

3

godbolt.org通过禁止 s中的绝对路径和相对路径解决了类似的问题#include

输入:

#include "/etc/passwd"

输出:

<stdin>:1:1: no absolute or relative includes please
Compilation failed

这可以通过在调用编译器之前在源上运行一个简单的检查器来实现。检查器只需 grep#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*include\s*["<]\s*/'
}

relative_includes()
{
    join_lines "$1"|grep '^\s*#\s*include'|fgrep '../'
}

includes_via_defines()
{
    join_lines "$1"|grep '^\s*#\s*include\s*[^"< \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包含绝对或相对路径的 s。它还检测通过如下宏完成的包含(这可以被滥用来解决路径检查):

#define HEADER "/etc/password"
#include HEADER
于 2016-09-01T17:39:29.220 回答