我编写了一个程序,孩子(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()'函数,还是我必须采取进一步的安全措施?
代码说明:
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
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)