Why the need of eval() in this code snippet?

188 views Asked by At

I am currently working on a small project in python using an API layer called "pybtsync" that provides an direct python access for BTSync. I tried to familiarize myself with it by looking at its source code where I found this:

def _request_function(self, method_name, arguments='', key=None):
    URL = 'http://' + self._address + ':' + self._port +'/api?method=' + method_name + '&' + arguments
    request = requests.get(URL, auth=(self._login, self._password))
    request_data = eval(request.text)
    if key is not None:
        return request_data[key]
    return request_data

I know that the API from BTsync returns in json formatting. So why isn't a json.load(request.text) not sufficient? I see a potential security issue with using eval() here. Is there any reason I do not see?

The whole code from pybtsync can be found here: https://github.com/tiagomacarios/pybtsync/blob/master/pybtsync/pybtsync.py#L239

For more context about the BTSync api: http://www.bittorrent.com/sync/developers/api

2

There are 2 answers

0
Martijn Pieters On BEST ANSWER

Yes, that is a security issue; if I can alter the DNS server your code uses or use a man-in-the-middle server then I can send you arbitrary Python code.

And if the API was ever updated to include JSON null or boolean values, the eval() call would fail for regular JSON responses as well.

The code should call request.json() instead.

2
miushock On

eval in interpreted language means invoke interpreter itself on target text, in other words, trying to parse and execute the text as a program.

In your case the result is json formated "string", not a json object, invoking eval on it will parse the string thus giving you an object, additionally, json.load will return unicode strings, while eval wont