Use secrets module for generating new API keys and passwords

The implementation of `random.choice()` uses the Mersenne Twister, the
output of which is predictable by observing previous output, and is as
such unsuitable for security-sensitive applications. A cryptographically
secure pseudorandom number generator - which the `secrets` module relies
on - should be used instead in those instances.
This commit is contained in:
Dominic Zöller 2021-11-07 19:54:19 +01:00 committed by zoeller-freinet
parent 9f46188c7e
commit 51a7f636b0
2 changed files with 4 additions and 4 deletions

View File

@ -1,4 +1,4 @@
import random
import secrets
import string
import bcrypt
from flask import current_app
@ -30,7 +30,7 @@ class ApiKey(db.Model):
self.accounts[:] = accounts
if not key:
rand_key = ''.join(
random.choice(string.ascii_letters + string.digits)
secrets.choice(string.ascii_letters + string.digits)
for _ in range(15))
self.plain_key = rand_key
self.key = self.get_hashed_password(rand_key).decode('utf-8')

View File

@ -30,7 +30,7 @@ from ..decorators import (
apikey_is_admin, apikey_can_access_domain, api_role_can,
apikey_or_basic_auth,
)
import random
import secrets
import string
api_bp = Blueprint('api', __name__, url_prefix='/api/v1')
@ -687,7 +687,7 @@ def api_create_user():
if not plain_text_password and not password:
plain_text_password = ''.join(
random.choice(string.ascii_letters + string.digits)
secrets.choice(string.ascii_letters + string.digits)
for _ in range(15))
if not role_name and not role_id:
role_name = 'User'