Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Safely evaluate string in Python to call hashlib

Tags:

python

I would like to allow people to provide the name of a hash function as a means of digitally fingerprinting some object:

def create_ref(obj, hashfn='sha256'):
    """
    Returns a tuple of hexdigest and the method used to generate
    the digest.

    >>> create_ref({}, 'sha1')
    ('bf21a9e8fbc5a3846fb05b4fa0859e0917b2202f', 'sha1')
    >>> create_ref({}, 'md5')
    ('99914b932bd37a50b983c5e7c90ae93b', 'md5')
    """
    return (eval('hashlib.%s' % hashfn)(unicode(obj)).hexdigest(), hashfn)

Is hard coding hashlib sufficently robust to prevent abuse of eval?

like image 409
Tim McNamara Avatar asked Aug 10 '26 09:08

Tim McNamara


1 Answers

No.

If you apply some of the SQL Injection attack concepts, it would be conceviable for the user to supply something like this:

"sha1(...); some_evil_code(); hashlib.sha1"

Which would totally blow the "security" away by ending up like this:

"hashlib." + "sha1(...); some_evil_code(); hashlib.sha1" + "(your-original-code)"

Which would result in 3 statements being run (a fine one, and evil one, and a fine one).

(even if the above code has holes in it, the concept could still be exploited)


Instead, use the dynamic power of python to make this work!

TYPES = ('sha256', 'sha1', 'md5', ...)
def create_ref(obj, hashfn='sha256'):
   if hashfn not in TYPES:
      raise ValueError("bad type")

   # look up the actual method
   fun = getattr(hashlib, hashfn)

   # and call it on `obj`
   fun(...)

Food for thought!

like image 117
gahooa Avatar answered Aug 12 '26 23:08

gahooa



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!