我有一个网络应用程序。作为其中的一部分,我需要应用程序的用户能够编写(或复制和粘贴)非常简单的脚本来运行他们的数据。
脚本确实非常简单,性能只是最小的问题。脚本的复杂性的例子我的意思是:
ratio = 1.2345678
minimum = 10
def convert(money)
return money * ratio
end
if price < minimum
cost = convert(minimum)
else
cost = convert(price)
end
其中价格和成本是全局变量(我可以将这些变量提供给环境并在计算后访问)。
但是,我确实需要保证一些东西。任何运行的脚本都无法访问Python环境。他们无法导入东西,调用我没有明确公开的方法,读取或写入文件,生成线程等等。我需要完全锁定。
我需要能够对脚本运行的“周期”数量进行硬限制。 Cycles是这里的通用术语。如果语言是字节编译的,则可能是VM指令。 Apply-调用Eval / Apply循环。或者只是通过一些运行脚本的中央处理循环进行迭代。细节并不像我能够在短时间内停止运行并向所有者发送电子邮件并说“你的脚本似乎只是添加几个数字而不是将它们排除在外”而非重要。
它必须在Vanilla未修补的CPython上运行。
到目前为止,我一直在编写自己的DSL来执行此任务。我能做到。但我想知道我是否可以建立在巨人的肩膀上。是否有可用于Python的迷你语言?
有很多hacky Lisp变种(即使是我在Github上写过的),但是我更喜欢具有更多非专业语法的东西(比如更多的C或Pascal),并且我认为这是一个替代自己编码我想要更成熟的东西。
有什么想法吗?
答案 0 :(得分:12)
以下是我对此问题的看法。要求用户脚本在vanilla CPython中运行意味着您需要为您的迷你语言编写解释器,或者将其编译为Python字节码(或使用Python作为源语言),然后在执行之前“清理”字节码。
基于用户可以写的假设,我已经找到了一个快速的例子 他们的Python脚本,源和字节码可以充分 通过从解析中过滤不安全语法的某种组合进行清理 树和/或从字节码中删除不安全的操作码。
解决方案的第二部分要求用户脚本字节码为 由监督任务定期中断,这将确保用户 脚本不超过某些操作码限制,并且所有这些都在vanilla CPython上运行。
我的尝试摘要,主要集中在问题的第二部分。
希望这至少会朝着正确的方向发展。我很想听 当你到达时,更多关于你的解决方案。
lowperf.py
的源代码:
# std
import ast
import dis
import sys
from pprint import pprint
# vendor
import byteplay
import greenlet
# bytecode snippet to increment our global opcode counter
INCREMENT = [
(byteplay.LOAD_GLOBAL, '__op_counter'),
(byteplay.LOAD_CONST, 1),
(byteplay.INPLACE_ADD, None),
(byteplay.STORE_GLOBAL, '__op_counter')
]
# bytecode snippet to perform a yield to our watchdog tasklet.
YIELD = [
(byteplay.LOAD_GLOBAL, '__yield'),
(byteplay.LOAD_GLOBAL, '__op_counter'),
(byteplay.CALL_FUNCTION, 1),
(byteplay.POP_TOP, None)
]
def instrument(orig):
"""
Instrument bytecode. We place a call to our yield function before
jumps and returns. You could choose alternate places depending on
your use case.
"""
line_count = 0
res = []
for op, arg in orig.code:
line_count += 1
# NOTE: you could put an advanced bytecode filter here.
# whenever a code block is loaded we must instrument it
if op == byteplay.LOAD_CONST and isinstance(arg, byteplay.Code):
code = instrument(arg)
res.append((op, code))
continue
# 'setlineno' opcode is a safe place to increment our global
# opcode counter.
if op == byteplay.SetLineno:
res += INCREMENT
line_count += 1
# append the opcode and its argument
res.append((op, arg))
# if we're at a jump or return, or we've processed 10 lines of
# source code, insert a call to our yield function. you could
# choose other places to yield more appropriate for your app.
if op in (byteplay.JUMP_ABSOLUTE, byteplay.RETURN_VALUE) \
or line_count > 10:
res += YIELD
line_count = 0
# finally, build and return new code object
return byteplay.Code(res, orig.freevars, orig.args, orig.varargs,
orig.varkwargs, orig.newlocals, orig.name, orig.filename,
orig.firstlineno, orig.docstring)
def transform(path):
"""
Transform the Python source into a form safe to execute and return
the bytecode.
"""
# NOTE: you could call ast.parse(data, path) here to get an
# abstract syntax tree, then filter that tree down before compiling
# it into bytecode. i've skipped that step as it is pretty verbose.
data = open(path, 'rb').read()
suite = compile(data, path, 'exec')
orig = byteplay.Code.from_code(suite)
return instrument(orig)
def execute(path, limit = 40):
"""
This transforms the user's source code into bytecode, instrumenting
it, then kicks off the watchdog and user script tasklets.
"""
code = transform(path)
target = greenlet.greenlet(run_task)
def watcher_task(op_count):
"""
Task which is yielded to by the user script, making sure it doesn't
use too many resources.
"""
while 1:
if op_count > limit:
raise RuntimeError("script used too many resources")
op_count = target.switch()
watcher = greenlet.greenlet(watcher_task)
target.switch(code, watcher.switch)
def run_task(code, yield_func):
"This is the greenlet task which runs our user's script."
globals_ = {'__yield': yield_func, '__op_counter': 0}
eval(code.to_code(), globals_, globals_)
execute(sys.argv[1])
以下是一个示例用户脚本user.py
:
def otherfunc(b):
return b * 7
def myfunc(a):
for i in range(0, 20):
print i, otherfunc(i + a + 3)
myfunc(2)
以下是一个示例运行:
% python lowperf.py user.py
0 35
1 42
2 49
3 56
4 63
5 70
6 77
7 84
8 91
9 98
10 105
11 112
Traceback (most recent call last):
File "lowperf.py", line 114, in <module>
execute(sys.argv[1])
File "lowperf.py", line 105, in execute
target.switch(code, watcher.switch)
File "lowperf.py", line 101, in watcher_task
raise RuntimeError("script used too many resources")
RuntimeError: script used too many resources
答案 1 :(得分:4)
它是Python中的JavaScript解释器,主要用于在Python中嵌入JS。
值得注意的是,它提供了递归和循环的检查和上限。正如所需。
它可以让您轻松地为JavaScript代码提供python函数。
默认情况下,它不会公开主机的文件系统或任何其他敏感元素。
答案 2 :(得分:2)
尝试Lua。你提到的语法几乎与Lua相同。见How could I embed Lua into Python 3.x?
答案 3 :(得分:2)
我还不知道有什么能真正解决这个问题。
我认为你能做的最简单的事情就是在python中编写自己版本的python虚拟机。
我经常想到像Cython这样的东西,所以你可以把它作为一个模块导入,你可以依靠大部分硬盘的现有运行时间。
您可能已经能够使用PyPy生成python-in-python解释器,但PyPy的输出是执行一切的运行时,包括为内置类型实现等效的底层PyObjects以及所有这些,我认为对于这种事情来说这太过分了。
您真正需要的是在执行堆栈中像Frame一样工作的东西,然后是每个操作码的方法。我认为你甚至不必自己实施它。您可以编写一个将现有框架对象暴露给运行时的模块。
无论如何,那么你只需维护自己的帧对象堆栈并处理字节码,你可以用每秒字节码或其他任何东西来限制它。
答案 4 :(得分:1)
为什么不在pysandbox http://pypi.python.org/pypi/pysandbox/1.0.3中使用python代码?
答案 5 :(得分:1)
看看LimPy。它代表有限的Python,专为此目的而构建。
有一个环境,用户需要编写基本逻辑来控制用户体验。我不知道它会如何与运行时限制相互作用,但我想如果你愿意写一些代码,你就可以做到。
答案 6 :(得分:1)
我使用Python作为早期项目的“迷你配置语言”。我的方法是获取代码,使用parser
模块解析它,然后遍历生成的代码的AST并踢出“不允许”的操作(例如,定义类,称为__
方法等。 )。
执行此操作后,创建了一个合成环境,其中只包含“允许”的模块和变量,并评估其中的代码以获取可以运行的内容。
它对我很有用。我不知道它是否是防弹,特别是如果你想给你的用户更多的力量比我的配置语言。
至于时间限制,您可以在单独的线程或进程中运行程序,并在一段固定的时间后终止它。
答案 7 :(得分:0)
制作真正DSL的最简单方法是ANTLR,它有一些流行语言的语法模板。