Une couche de protection pour l'évaluation
Afficher les exemples · Rapport Bogue
Je sais que beaucoup de gens ne se soucient pas des motivations derrière un programme, donc j'ai mis l'installation au sommet.
python3 -m pip install cvalpy - m pip install cvalUn script décemment simple qui utilise une expression régulière pour ajouter une couche de protection à l'évaluation. Pourquoi? Eh bien, je n'arrête pas de voir "Eval est vraiment dangereux" et "Eval est une mauvaise pratique" . Toutes ces déclarations ont une certaine validité, et il y a presque toujours une meilleure façon de faire ce que vous voulez accomplish. CVAL s'attaque à l'état d'esprit "Eval est vraiment dangereux" , si vous devez utiliser EVAL pour un projet public utilise CVAL.
Je vous encourage à briser mon script, à signaler tous les bogues ou les vulnérabilités ici, merci!
Ces exemples sont axés uniquement sur la sécurité plutôt que des exemples pratiques du monde réel.
# :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