From f92d52c3a425495ffd5bb19abd11ee79806520be Mon Sep 17 00:00:00 2001 From: Jeremy Cline Date: Sep 27 2018 13:47:19 +0000 Subject: Don't generate API keys with random.choice Pagure uses pagure.lib.login.id_generator to generate API tokens, hook tokens, etc, which is backed by random.choice. random.choice is backed by the Mersenne Twister PRNG, which is *not* a CSPRNG and should never be used for any security-related purposes[0]. Use the secrets API if it's available, and fall back to random backed by /dev/urandom. [0] https://docs.python.org/3/library/random.html Signed-off-by: Jeremy Cline --- diff --git a/pagure/lib/login.py b/pagure/lib/login.py index 4d9b33e..2853c51 100644 --- a/pagure/lib/login.py +++ b/pagure/lib/login.py @@ -11,7 +11,14 @@ from __future__ import unicode_literals -import random +try: + # Provided in Python 3.6+ + from secrets import choice as random_choice +except ImportError: + # Fall back to SystemRandom, backed by os.urandom + import random + random = random.SystemRandom() + random_choice = random.choice import string import hashlib import bcrypt @@ -32,7 +39,7 @@ def id_generator(size=15, chars=string.ascii_uppercase + string.digits): :arg chars: the list of characters that can be used in the idenfitier. """ - return "".join(random.choice(chars) for x in range(size)) + return "".join(random_choice(chars) for x in range(size)) def get_session_by_visitkey(session, sessionid):