Reputation: 1259
I'm doing a test web service project where I need to create some dynamic variables. To implement this, I have no option but using exec() function like follow.
for parameter in parameter_names:
if parameter["type"] == "number":
exec("%s= %s(request.args.get('%s'))"%(parameter["name"],"float",parameter["name"]))
para_collection[parameter["name"]] = eval(parameter["name"])
else:
exec("%s= %s(request.args.get('%s'))"%(parameter["name"],"str",parameter["name"]))
para_collection[parameter["name"]] = eval(parameter["name"])
Here I accept values from a web call and assign them to dynamic variable names.Even though this code gives me the expected result, I have seen number of StackOverflow posts, mentioning security risks of exec() function. Therefore I would like to evaluate this code for security.
What scenarios I need to test ? If not exec() what are the alternatives ?
Upvotes: 0
Views: 1216
Reputation: 6629
You need to validate that parameter["name"]
is safe. The best way to do this is to white list a set of values that are allowed to be provided by the user. As is, there are all sorts of dangerous things an attacker can do to your code -- especially remote code execution.
Example: attacker sends in import os\nos.system("rm -rf *") #
for parameter["name"]
(assuming Linux OS but attack can be adapted for other OS). Ouch, you lose a lot of data.
More generally, the current implementation allows the attacker to create a web shell or reverse shell that allows him to execute anything on your server as if he were local.
What is the format that your parameter["name"]
can take? If it is only alphanumeric, then validation can be a regex that checks whether the values match an alphanumeric pattern. If not, return a 400 error to the user. If valid, allow the command to proceed.
See guide: Secure Coding: Understanding Input Validation.
Upvotes: 2