Last active
November 8, 2023 12:07
-
-
Save mkolod/853cda9950b898d056ac149abc45417a to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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')) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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