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?
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!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With