防止用户上传的代码执行恶意任务

Prevent user uploaded code from performing malicious tasks

对于 class 项目,我们正在创建一个网络项目,用户可以在其中上传 ai 脚本(python 代码)以玩游戏。我已经完成文件上传部分,但我担心安全和防止恶意代码。

如何防止用户向应用上传恶意代码?

  • 使用 PyPy 创建一个 python 沙箱 AND/OR
  • 扫描并去除潜在危险的class 导入(fs、系统..等)

repl 是沙盒方法的实例。

我建议您不要按关键字过滤。有更可靠的方法来阻止恶意代码。我写了这个小片段来说明恶意代码如何潜在地规避字符串过滤过程:

test = """
def f():
    import os
    print((os.name))
f()
"""
obfus = []
for c in test: obfus.append(chr(ord(c) + 1))
obfus = ''.join(obfus)
obfus.replace("os", "**")
def hidden_things():
    print_os = []
    for c in obfus: print_os.append(chr(ord(c) - 1))
    exec(''.join(print_os))
hidden_things()

恶意编码人员经常想出非常有创意的方法来规避安全措施。这是一个非常简单的例子,说明比我聪明的人可以完成什么。

修正:

我在这个网站上发现了几个相关问题:

  • Preventing Python code from importing certain modules?
  • How can I block a Python stdlib module from being imported?
  • How to make web based python interactive shell

在语言级别进行沙盒几乎是不可能的,所以你有两个选择:

  1. 使用虚拟化层(如 VirtualBox)或更轻量级的东西(如 Google Native Client、LXC 或 Docker.
  2. 对 Python 进程进行沙盒处理
  3. 使用为您做这件事的服务,喜欢http://repl.it/api