Eine Schutzschicht für eval
Beispiele anzeigen · Fehler melden
Ich weiß, dass viele Menschen die Motive hinter einem Programm nicht interessieren, also habe ich die Installation an die Spitze gestellt.
python3 -m pip install cvalpy - m pip install cvalEin anständig einfaches Skript, das regelmäßig Ausdruck verwendet, um die Bewertung eine Schutzebene hinzuzufügen. Warum? Nun, ich sehe immer wieder "Eval wirklich ist gefährlich" und "Eval ist eine schlechte Praxis" . All diese Aussagen haben eine gewisse Gültigkeit, und es gibt fast immer eine bessere Möglichkeit, das zu tun, was Sie sich unterhalten möchten. CVAL wächst die Denkweise "eval wirklich ist gefährlich" an, wenn Sie Eval für ein öffentliches Projekt verwenden müssen, um CVAL zu verwenden.
Ich ermutige Sie, mein Skript zu brechen und Fehler oder Schwachstellen hier zu melden, danke!
Diese Beispiele konzentrieren sich ausschließlich auf die Sicherheit, als auf praktische Beispiele der realen Welt.
# :NOTE: modules is False by default, and the reason we allow function calls
# is to see the error given when trying to import a module.
cval ( '__import__("os")' , calls = True , modules = False ) cval.IllegalSource: Cval panicked due to an attempted illegal import of the module "os"
cval ( '__import__("os")' , allowed_modules = [ "os" ], allowed_calls = [ "import" ]) cval ( 'print("Hello, World!")' , calls = False ) cval.IllegalSource: Cval panicked due to an illegal function call in source! Attemped call to "print"
cval ( 'print("Hello, World!")' , allowed_calls = [ "print" ]) foo = "bar"
def foobar ():
# :NOTE: `globals` doesn't need to be passed in this case
# this is only done here for clarity
cval ( 'print(foo)' , globals = globals (), allowed_calls = [ "print" ]) # Will not be able to access "foo"
foobar () cval.SuspiciousSource: Cval found global variable "foo" in the source, killing for safety.
foo = "bar"
def foobar ():
cval ( 'print(foo)' , globals = globals (), allowed_global_vars = [ "foo" ], allowed_calls = [ "print" ])
foobar () bar
foo = "bar"
bar = "foo"
def foobar ():
cval ( 'print(bar+foo")' , globals = globals (), allowed_global_vars = [ "*" ], allowed_calls = [ "print" ])
foobar () foobar
def fizzbuzz ():
fizz = "buzz"
cval ( 'print(fizz)' , locals = locals ()) # Will not be able to access "fizz"
fizzbuzz () cval.SuspiciousSource: Cval found local variable "fizz" in the source, killing for safety.
def fizzbuzz ():
fizz = "buzz"
cval ( 'print(fizz)' , locals = locals (), allowed_local_vars = [ "fizz" ], allowed_calls = [ "print" ])
fizzbuzz () buzz
def fizzbuzz ():
fizz = "buzz"
buzz = "fizz"
cval ( 'print(buzz+fizz)' , locals = locals (), allowed_local_vars = [ "*" ], allowed_calls = [ "print" ])
fizzbuzz () fizzbuzz