From 098c772da9670c37df5e85bf0ad03c086a648d13 Mon Sep 17 00:00:00 2001 From: Josh W Date: Sat, 15 Feb 2020 18:01:13 -0500 Subject: [PATCH] Safer password/token generation for the DJ. --- .../core/migrations/0002_create_dj_user.py | 16 +++++++++------- savepointradio/core/utils.py | 13 ------------- 2 files changed, 9 insertions(+), 20 deletions(-) diff --git a/savepointradio/core/migrations/0002_create_dj_user.py b/savepointradio/core/migrations/0002_create_dj_user.py index 792b783..c6f27d6 100644 --- a/savepointradio/core/migrations/0002_create_dj_user.py +++ b/savepointradio/core/migrations/0002_create_dj_user.py @@ -2,20 +2,22 @@ import binascii import os +import secrets +import string from django.conf import settings from django.contrib.auth.hashers import make_password +from django.utils.crypto import get_random_string from django.db import migrations, models -from core.utils import generate_password - def create_dj_user(apps, schema_editor): User = apps.get_model('core', 'RadioUser') Token = apps.get_model('authtoken', 'Token') db_alias = schema_editor.connection.alias - new_password = generate_password() + chars = string.ascii_letters + string.digits + string.punctuation + new_password = get_random_string(length=32, allowed_chars=chars) dj = User(email=settings.RADIO_DJ_EMAIL, name=settings.RADIO_DJ_NAME, password=make_password(new_password), @@ -24,10 +26,10 @@ def create_dj_user(apps, schema_editor): is_dj=True) dj.save(using=db_alias) - # Since 'post_save' is impervious to migration scripts, this is pulled - # directly from the authtoken code for key generation. Otherwise, key will - # be blank. - token = Token(key=binascii.hexlify(os.urandom(20)).decode(), user=dj) + # Since 'post_save' is impervious to migration scripts, this will be + # created here instead. Otherwise, key will be blank and we don't want + # that for the DJ account. + token = Token(key=secrets.token_hex(20), user=dj) token.save(using=db_alias) with open(os.path.join(settings.PROJECT_DIR, '.djinfo'), 'w') as f: diff --git a/savepointradio/core/utils.py b/savepointradio/core/utils.py index 91070d8..cf556a0 100644 --- a/savepointradio/core/utils.py +++ b/savepointradio/core/utils.py @@ -36,19 +36,6 @@ FILE_IRI_PATTERN = ( ) -def generate_password(length=32): - ''' - Quick and dirty random password generator. - - ***WARNING*** - Although this is likely "good enough" to create a secure - password, there are no validations (suitible entropy, dictionary words, - etc.) and should not be completely trusted. YOU HAVE BEEN WARNED. - ''' - chars = string.ascii_letters + string.digits + string.punctuation - rng = random.SystemRandom() - return ''.join([rng.choice(chars) for i in range(length)]) - - def get_len(rawqueryset): ''' Adds/Overrides a dynamic implementation of the length protocol to the