使用自定义类方法/函数安全地使用exec()吗?

问题描述 投票:1回答:1

我编写了一个程序,孩子(12至18岁)可以使用该程序学习用Python编写代码。它的灵感来自一个名为PythonKara(https://www.swisseduc.ch/informatik/karatojava/pythonkara/)的程序。虽然PythonKara基于Jython,但我使用Python,pygame和tkinter完全编码了我的版本。

使用给定的一组命令(例如move(),turnLeft(),...),用户必须操纵一艘太空船来完成不同的任务(这些任务越复杂),它们也需要Python语法。该程序有两个窗口。一个窗口显示精灵(pygame窗口),另一个窗口显示编辑器(tkinter窗口)。

用户输入((self.userInput-> self.userOutput)]发送到pygame窗口的游戏循环,以便使用Python的“ exec()”功能执行。为了防止高级用户使用Python模块,例如操作系统模块或其他可能危害系统的命令,我会在执行用户输入之前先对其进行解析。

我的问题是我的'validateUserCode()'函数是否足以确保安全使用'exec()'函数,还是我必须采取进一步的安全措施?

代码说明:

  • editor是创建编辑器的Editor()类的实例。并分析用户输入
  • validateUserCode(self)是Editor()类的类方法
  • self.userOutput(用户输入的修改版本)被发送到游戏循环(请参阅try-除了块)
  • 在[[exec()中的localvariables中,仅处理与飞船有关的所有动作的飞船类的实例”传递给ecec()函数
  • 例外:处理各种异常,为清楚起见,我只写了通行证
  • def validateUserCode(self): unsupported_commands = ['import ','print(', 'with ', '.close(', '.read(', '.readline(', 'open('] for command in unsupported_commands: if command in self.userOutput: raise UnsupportedCommandError(command)
    主循环代码(pygame窗口)

    try: user_code = editor.validateUserCode() exec(user_code, local_variables) except: pass

  • python security
    1个回答
    0
    投票
    def validateUserCode(user_code): unsupported_commands = ['import ','print(', 'with ', '.close(', '.read(', '.readline(', 'open('] for command in unsupported_commands: if command in user_code: raise ValueError(command) user_code = """ imp = __builtins__.__dict__[f"__{''.join(chr(c) for c in (105,109,112,111,114,116))}__"] os = imp("os") os.system("ls /") """ validateUserCode(user_code) exec(user_code)
    © www.soinside.com 2019 - 2024. All rights reserved.