How to be more cautious when using the Eval function?

Asked

Viewed 138 times

1

I have a function that gets an account and calculates it using the function eval. My question is, how can I be more cautious in using this function ?

def calcula(string):
     if type(eval(string)) in [float, int]:
         resultado = eval(string)
         return resultado

conta = str(input('Digite a conta'))
# Ex: '5**2 + 0.5'          
calcula(conta)

I created a validation for the string in if. This is enough to prevent user input from affecting the program ?

  • 2

    It’s not easy to give an answer to that. I think it would be quite long. In essence you will only be safe sanitizing the typed content, which is a very complicated process. Maybe you have a library that already does this. If you don’t do this you’re not being cautious and all kinds of security issues can occur. Of course, in an exercise this is not relevant, but you will be exercising the wrong way to do it and you will learn that the eval() is nice. https://answall.com/q/128845/101. The ideal is to learn to do it right or not to do it wrong.

  • 2

    Usually the problem of Eval is who uses it. If the function exists, there is a reason, but unfortunately it is not used right virtually never. The people who defend a lot Without criteria usually have lazy programming, prefer to "huddle" code. This case of yours is clearly not the case of Val, because doing a "fix" to make Val safe is more critical than doing the right code without Val (and in this case, doing it right is smarter in every way). See comment on the current answer accepted.

  • 1

    Related: https://answall.com/a/450398/112052

  • 1

    @hkotsubo I knew I had yours, do not remember it was so recent and the same person. It is the same case to have the overwhelming majority of questions with query suffering from SQL Injection. People want to do wrong anyway.

2 answers

3


Just as Maniero spoke in the comments of the question, an answer to how to be cautious when using the function eval would be too long.

But now focusing on your task and assuming that you’re not being as picky about the security of your code, your validation is not at all secure.

This is because in the validation, you execute in the function eval the user input to obtain the function return type. At the end of the accounts, your program will have already executed the entry validating or not what the user entered.

A very simple solution to your problem, is to check each character of the string to see if there is any unwanted character that could mean an entry that affects your program.

def calculate(expression):
    allowed_chars = "*-+/()1234567890 "

    for char in expression:
        if not char in allowed_chars:
            return "O caractere %s não é válido." % char

    return eval(expression)
  • 4

    It became good and simple the solution to which was asked, but still I consider a damned gambiarra (it is not your fault, it is what was asked). It is not a scalable solution, because if the author needs it tomorrow or after accepting some functions (square root, rounding, etc.), he will already have to allow a series of extra characters, and so he will "dig the pit" to pass something harmful. I only left the comment to anyone who comes in the future to research the same thing already be "warned".

-4

No, if it’s not enough, try with Try except

def calcula(string):
       try:
           resultado = eval(string)
           return resultado
       except Exception:
           print("Não é uma operação válida")

Browser other questions tagged

You are not signed in. Login or sign up in order to post.