Skip to content

Instantly share code, notes, and snippets.

@mkolod
Last active November 8, 2023 12:07
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mkolod/853cda9950b898d056ac149abc45417a to your computer and use it in GitHub Desktop.
Save mkolod/853cda9950b898d056ac149abc45417a to your computer and use it in GitHub Desktop.
#!/usr/bin/python3
# Python 3 changes hash seeds upon interpreter start.
# https://docs.python.org/3/reference/datamodel.html#object.__hash__
#
# This was to fix the following vulnerability:
# http://ocert.org/advisories/ocert-2011-003.html
#
# For non-web apps, the hash non-determinism between interpreter runs
# can be fixed by setting an env var:
# export PYTHONHASHSEED=1234
# But, if the interpreter was started and the env var
# wasn't set ahead of time, here's a fix that can be
# done at runtime from the interpreter itself.
import os
import sys
if __name__ == '__main__':
# Set hash seed and restart interpreter.
# This will be done only once if the env var is clear.
if not os.environ.get('PYTHONHASHSEED'):
os.environ['PYTHONHASHSEED'] = '1234'
os.execv(sys.executable, ['python3'] + sys.argv)
print(hash('foo'))
@mkolod
Copy link
Author

mkolod commented Jan 5, 2018

Execution example:

$ python3 --version
Python 3.5.2

$ python3 fixed_hash.py
-8715801143494849942

$ python3 fixed_hash.py
-8715801143494849942

$ PYTHONHASHSEED="random" python3 fixed_hash.py
8760842921345983771

$ PYTHONHASHSEED="random" python3 fixed_hash.py
-456391045329298245

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment