mirror of
https://github.com/karpathy/nanochat.git
synced 2025-12-06 04:12:13 +00:00
harden eval: prevent the calc tool from accessing globals and locals
By passing empty globals() and locals() to eval() we can prevent simple
malicious cases where the user gets the model to output something like
```<global variable/func> or "a".count("a")```
e.g.
```signal.raise_signal(9) or "a".count("a")``` which would kill the process.
or one could maybe get it to output secrets etc.
I think to make it 100% secure one would need to parse the AST and only execute secure nodes but this should make it much more robust.
This commit is contained in:
parent
05a051dbe9
commit
fca2b8cd07
|
|
@ -37,7 +37,7 @@ def eval_with_timeout(formula, max_time=3):
|
||||||
with timeout(max_time, formula):
|
with timeout(max_time, formula):
|
||||||
with warnings.catch_warnings():
|
with warnings.catch_warnings():
|
||||||
warnings.simplefilter("ignore", SyntaxWarning)
|
warnings.simplefilter("ignore", SyntaxWarning)
|
||||||
return eval(formula)
|
return eval(formula, {"__builtins__": {}}, {})
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
signal.alarm(0)
|
signal.alarm(0)
|
||||||
# print(f"Warning: Failed to eval {formula}, exception: {e}") # it's ok ignore wrong calculator usage
|
# print(f"Warning: Failed to eval {formula}, exception: {e}") # it's ok ignore wrong calculator usage
|
||||||
|
|
|
||||||
Loading…
Reference in New Issue
Block a user