Initial mfa support (for internal users) #93591
@ -13,11 +13,11 @@ from django.template import defaultfilters
|
||||
from django.utils import timezone
|
||||
from django.utils.translation import gettext_lazy as _
|
||||
from django_otp.oath import TOTP
|
||||
from django_otp.plugins.otp_totp.models import TOTPDevice
|
||||
from otp_agents.views import OTPTokenForm
|
||||
|
||||
from .models import User, OAuth2Application
|
||||
from .recaptcha import check_recaptcha
|
||||
from mfa.models import EncryptedTOTPDevice
|
||||
import bid_main.tasks
|
||||
|
||||
log = logging.getLogger(__name__)
|
||||
@ -492,7 +492,7 @@ class TotpMfaForm(forms.Form):
|
||||
)
|
||||
key = forms.CharField(widget=forms.HiddenInput)
|
||||
name = forms.CharField(
|
||||
max_length=TOTPDevice._meta.get_field('name').max_length,
|
||||
max_length=EncryptedTOTPDevice._meta.get_field('name').max_length,
|
||||
widget=forms.TextInput(
|
||||
attrs={"placeholder": "device name (for your convenience)"},
|
||||
),
|
||||
@ -518,7 +518,7 @@ class TotpMfaForm(forms.Form):
|
||||
def save(self):
|
||||
key = self.cleaned_data.get('key')
|
||||
name = self.cleaned_data.get('name')
|
||||
TOTPDevice.objects.create(key=key, name=name, user=self.user)
|
||||
EncryptedTOTPDevice.objects.create(encrypted_key=key, key='', name=name, user=self.user)
|
||||
|
||||
@classmethod
|
||||
def sign(cls, user, key):
|
||||
|
@ -15,9 +15,6 @@ from django.core.mail import send_mail
|
||||
from django.db import models, transaction
|
||||
from django.db.models import Q
|
||||
from django import urls
|
||||
from django_otp import devices_for_user
|
||||
from django_otp.plugins.otp_static.models import StaticDevice
|
||||
from django_otp.plugins.otp_totp.models import TOTPDevice
|
||||
from django.templatetags.static import static
|
||||
from django.utils.deconstruct import deconstructible
|
||||
from django.utils import timezone
|
||||
@ -27,6 +24,7 @@ import user_agents
|
||||
|
||||
from . import fields
|
||||
from . import hashers
|
||||
from mfa.models import EncryptedRecoveryDevice, EncryptedTOTPDevice, devices_for_user
|
||||
import bid_main.file_utils
|
||||
import bid_main.utils
|
||||
|
||||
@ -548,9 +546,9 @@ class User(AbstractBaseUser, PermissionsMixin):
|
||||
def mfa_devices_per_category(self):
|
||||
devices_per_category = defaultdict(list)
|
||||
for device in devices_for_user(self):
|
||||
if isinstance(device, StaticDevice):
|
||||
if isinstance(device, EncryptedRecoveryDevice):
|
||||
devices_per_category['recovery'].append(device)
|
||||
if isinstance(device, TOTPDevice):
|
||||
if isinstance(device, EncryptedTOTPDevice):
|
||||
devices_per_category['totp'].append(device)
|
||||
return devices_per_category
|
||||
|
||||
|
@ -51,7 +51,7 @@ Multi-factor Authentication Setup
|
||||
{% with recovery=devices_per_category.recovery.0 %}
|
||||
{% if recovery %}
|
||||
<div class="mb-3">
|
||||
{% with code_count=recovery.token_set.count %}
|
||||
{% with code_count=recovery_codes|length %}
|
||||
{{ code_count }} recovery code{{ code_count|pluralize }} remaining
|
||||
{% if recovery_codes %}
|
||||
<a href="?display_recovery_codes=" class="btn">Hide</a>
|
||||
|
@ -9,15 +9,13 @@ from django.urls import reverse, reverse_lazy
|
||||
from django.views.generic import TemplateView
|
||||
from django.views.generic.base import View
|
||||
from django.views.generic.edit import DeleteView, FormView
|
||||
from django_otp import devices_for_user
|
||||
from django_otp.models import Device
|
||||
from django_otp.plugins.otp_static.models import StaticDevice
|
||||
from django_otp.plugins.otp_totp.models import TOTPDevice, default_key
|
||||
from django_otp.util import random_hex
|
||||
import qrcode
|
||||
|
||||
from . import mixins
|
||||
from bid_main.forms import DisableMfaForm, TotpMfaForm
|
||||
from mfa.models import EncryptedRecoveryDevice, EncryptedTOTPDevice, devices_for_user
|
||||
|
||||
|
||||
class MfaView(mixins.MfaRequiredIfConfiguredMixin, TemplateView):
|
||||
@ -34,7 +32,8 @@ class MfaView(mixins.MfaRequiredIfConfiguredMixin, TemplateView):
|
||||
user_can_setup_recovery = False
|
||||
devices_per_category = user.mfa_devices_per_category()
|
||||
if self.request.GET.get('display_recovery_codes') and 'recovery' in devices_per_category:
|
||||
recovery_codes = [t.token for t in devices_per_category['recovery'][0].token_set.all()]
|
||||
recovery_device = devices_per_category['recovery'][0]
|
||||
recovery_codes = [t.encrypted_token for t in recovery_device.encryptedtoken_set.all()]
|
||||
if devices_per_category.keys() - {'recovery'}:
|
||||
user_can_setup_recovery = True
|
||||
return {
|
||||
@ -52,7 +51,7 @@ class DisableView(mixins.MfaRequiredMixin, FormView):
|
||||
|
||||
@transaction.atomic
|
||||
def form_valid(self, form):
|
||||
for device in devices_for_user(self.request.user, confirmed=None):
|
||||
for device in devices_for_user(self.request.user):
|
||||
device.delete()
|
||||
return super().form_valid(form)
|
||||
|
||||
@ -61,15 +60,17 @@ class GenerateRecoveryView(mixins.MfaRequiredIfConfiguredMixin, View):
|
||||
@transaction.atomic
|
||||
def post(self, request, *args, **kwargs):
|
||||
user = self.request.user
|
||||
if not list(filter(lambda d: not isinstance(d, StaticDevice), devices_for_user(user))):
|
||||
if not list(
|
||||
filter(lambda d: not isinstance(d, EncryptedRecoveryDevice), devices_for_user(user))
|
||||
):
|
||||
# Forbid setting up recovery codes unless the user already has some other method
|
||||
return HttpResponseBadRequest("can't setup recovery codes before other methods")
|
||||
user.staticdevice_set.all().delete()
|
||||
device = StaticDevice.objects.create(name='recovery', user=user)
|
||||
device = EncryptedRecoveryDevice.objects.create(name='recovery', user=user)
|
||||
for _ in range(10):
|
||||
# https://pages.nist.gov/800-63-3/sp800-63b.html#5122-look-up-secret-verifiers
|
||||
# don't use less than 64 bits
|
||||
device.token_set.create(token=random_hex(8).upper())
|
||||
device.encryptedtoken_set.create(encrypted_token=random_hex(8).upper())
|
||||
return redirect(reverse('bid_main:mfa') + '?display_recovery_codes=1#recovery-codes')
|
||||
|
||||
|
||||
@ -86,7 +87,7 @@ class TotpView(mixins.MfaRequiredIfConfiguredMixin, FormView):
|
||||
|
||||
def get_form(self, *args, **kwargs):
|
||||
kwargs = self.get_form_kwargs()
|
||||
key = self.request.POST.get('key', default_key())
|
||||
key = self.request.POST.get('key', random_hex(20))
|
||||
kwargs['initial']['key'] = key
|
||||
kwargs['initial']['signature'] = TotpMfaForm.sign(kwargs['user'], key)
|
||||
return TotpMfaForm(**kwargs)
|
||||
@ -101,7 +102,7 @@ class TotpView(mixins.MfaRequiredIfConfiguredMixin, FormView):
|
||||
key = context['form'].initial['key']
|
||||
b32key = b32encode(unhexlify(key)).decode('utf-8')
|
||||
context['manual_secret_key'] = b32key
|
||||
device = TOTPDevice(key=key, user=self.request.user)
|
||||
device = EncryptedTOTPDevice(encrypted_key=key, user=self.request.user)
|
||||
context['config_url'] = device.config_url
|
||||
image = qrcode.make(
|
||||
device.config_url,
|
||||
@ -126,7 +127,7 @@ class DeleteDeviceView(mixins.MfaRequiredMixin, DeleteView):
|
||||
for device in devices_for_user(self.request.user):
|
||||
if (
|
||||
device.persistent_id != kwargs['persistent_id']
|
||||
and not isinstance(device, StaticDevice)
|
||||
and not isinstance(device, EncryptedRecoveryDevice)
|
||||
):
|
||||
# there are other non-recovery devices, it's fine to delete this one
|
||||
return super().get(request, *args, **kwargs)
|
||||
|
@ -22,8 +22,6 @@ from django.views.decorators.cache import never_cache
|
||||
from django.views.generic import TemplateView, FormView
|
||||
from django.views.generic.base import View
|
||||
from django.views.generic.edit import UpdateView
|
||||
from django_otp import devices_for_user
|
||||
from otp_agents.forms import OTPTokenForm
|
||||
import loginas.utils
|
||||
import oauth2_provider.models as oauth2_models
|
||||
import otp_agents.views
|
||||
|
@ -36,9 +36,25 @@ PREFERRED_SCHEME = "https"
|
||||
# Update this to something unique for your machine.
|
||||
SECRET_KEY = os.getenv('SECRET_KEY', 'default-dev-secret')
|
||||
|
||||
# NACL_FIELDS_KEY is used to encrypt MFA shared secrets
|
||||
# !!!!!!!!!!!!
|
||||
# !!!DANGER!!! its loss or bad rotation will lock out all users with MFA!!!
|
||||
# !!!!!!!!!!!!
|
||||
# generate a prod key with ./manage.py createkey
|
||||
# and put it as a string in the .env file,
|
||||
# .encode('ascii') takes care of making the variable populated with a byte array
|
||||
NACL_FIELDS_KEY = os.getenv(
|
||||
'NACL_FIELDS_KEY', 'N5W|iA&lZ7iGsy92=qlr>~heUoH4ZX16pCEGG*R+'
|
||||
).encode('ascii')
|
||||
|
||||
# SECURITY WARNING: don't run with debug turned on in production!
|
||||
DEBUG = bool(os.getenv('DEBUG', False))
|
||||
|
||||
if not DEBUG and NACL_FIELDS_KEY == b'N5W|iA&lZ7iGsy92=qlr>~heUoH4ZX16pCEGG*R+':
|
||||
raise Exception('please override NACL_FIELDS_KEY in .env')
|
||||
if not DEBUG and SECRET_KEY == 'default-dev-secret':
|
||||
raise Exception('please override SECRET_KEY in .env')
|
||||
|
||||
TESTING = sys.argv[1:2] == ['test']
|
||||
|
||||
ALLOWED_HOSTS = os.getenv('ALLOWED_HOSTS', 'id.local').split(',')
|
||||
@ -65,10 +81,12 @@ INSTALLED_APPS = [
|
||||
"sorl.thumbnail",
|
||||
"django_admin_select2",
|
||||
"loginas",
|
||||
"nacl_encrypted_fields",
|
||||
"bid_main",
|
||||
"bid_api",
|
||||
"bid_addon_support",
|
||||
"background_task",
|
||||
"mfa",
|
||||
]
|
||||
|
||||
MIDDLEWARE = [
|
||||
|
0
mfa/__init__.py
Normal file
0
mfa/__init__.py
Normal file
6
mfa/apps.py
Normal file
6
mfa/apps.py
Normal file
@ -0,0 +1,6 @@
|
||||
from django.apps import AppConfig
|
||||
|
||||
|
||||
class MfaConfig(AppConfig):
|
||||
default_auto_field = 'django.db.models.BigAutoField'
|
||||
name = "mfa"
|
70
mfa/migrations/0001_initial.py
Normal file
70
mfa/migrations/0001_initial.py
Normal file
@ -0,0 +1,70 @@
|
||||
# Generated by Django 4.2.13 on 2024-08-13 11:33
|
||||
|
||||
from django.db import migrations, models
|
||||
import django.db.models.deletion
|
||||
import nacl_encrypted_fields.fields
|
||||
|
||||
|
||||
class Migration(migrations.Migration):
|
||||
|
||||
initial = True
|
||||
|
||||
dependencies = [
|
||||
('otp_static', '0003_add_timestamps'),
|
||||
('otp_totp', '0003_add_timestamps'),
|
||||
]
|
||||
|
||||
operations = [
|
||||
migrations.CreateModel(
|
||||
name='EncryptedTOTPDevice',
|
||||
fields=[
|
||||
(
|
||||
'totpdevice_ptr',
|
||||
models.OneToOneField(
|
||||
auto_created=True,
|
||||
on_delete=django.db.models.deletion.CASCADE,
|
||||
parent_link=True,
|
||||
primary_key=True,
|
||||
serialize=False,
|
||||
to='otp_totp.totpdevice',
|
||||
),
|
||||
),
|
||||
('encrypted_key', nacl_encrypted_fields.fields.NaClCharField(max_length=255)),
|
||||
],
|
||||
options={
|
||||
'abstract': False,
|
||||
},
|
||||
bases=('otp_totp.totpdevice',),
|
||||
),
|
||||
migrations.CreateModel(
|
||||
name='EncryptedRecoveryDevice',
|
||||
fields=[],
|
||||
options={
|
||||
'abstract': False,
|
||||
'proxy': True,
|
||||
'indexes': [],
|
||||
'constraints': [],
|
||||
},
|
||||
bases=('otp_static.staticdevice',),
|
||||
),
|
||||
migrations.CreateModel(
|
||||
name='EncryptedStaticToken',
|
||||
fields=[
|
||||
(
|
||||
'id',
|
||||
models.BigAutoField(
|
||||
auto_created=True, primary_key=True, serialize=False, verbose_name='ID'
|
||||
),
|
||||
),
|
||||
('encrypted_token', nacl_encrypted_fields.fields.NaClCharField(max_length=255)),
|
||||
(
|
||||
'device',
|
||||
models.ForeignKey(
|
||||
on_delete=django.db.models.deletion.CASCADE,
|
||||
related_name='encryptedtoken_set',
|
||||
to='mfa.encryptedrecoverydevice',
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
]
|
0
mfa/migrations/__init__.py
Normal file
0
mfa/migrations/__init__.py
Normal file
50
mfa/models.py
Normal file
50
mfa/models.py
Normal file
@ -0,0 +1,50 @@
|
||||
from binascii import unhexlify
|
||||
|
||||
from django.db import models
|
||||
from django_otp.plugins.otp_static.models import StaticDevice
|
||||
from django_otp.plugins.otp_totp.models import TOTPDevice
|
||||
from nacl_encrypted_fields.fields import NaClCharField
|
||||
|
||||
|
||||
class EncryptedRecoveryDevice(StaticDevice):
|
||||
class Meta(StaticDevice.Meta):
|
||||
abstract = False
|
||||
proxy = True
|
||||
|
||||
def verify_token(self, token):
|
||||
verify_allowed, _ = self.verify_is_allowed()
|
||||
if verify_allowed:
|
||||
match = self.encryptedtoken_set.filter(encrypted_token=token).first()
|
||||
if match is not None:
|
||||
match.delete()
|
||||
self.throttle_reset(commit=False)
|
||||
self.set_last_used_timestamp(commit=False)
|
||||
self.save()
|
||||
else:
|
||||
self.throttle_increment()
|
||||
else:
|
||||
match = None
|
||||
|
||||
return match is not None
|
||||
|
||||
|
||||
class EncryptedStaticToken(models.Model):
|
||||
device = models.ForeignKey(
|
||||
EncryptedRecoveryDevice, related_name='encryptedtoken_set', on_delete=models.CASCADE
|
||||
)
|
||||
encrypted_token = NaClCharField(max_length=255)
|
||||
|
||||
|
||||
class EncryptedTOTPDevice(TOTPDevice):
|
||||
encrypted_key = NaClCharField(max_length=255)
|
||||
|
||||
@property
|
||||
def bin_key(self):
|
||||
return unhexlify(self.encrypted_key.encode())
|
||||
|
||||
|
||||
def devices_for_user(user):
|
||||
return [
|
||||
*EncryptedRecoveryDevice.objects.filter(user=user).all(),
|
||||
*EncryptedTOTPDevice.objects.filter(user=user).all(),
|
||||
]
|
@ -15,6 +15,7 @@ django-background-tasks-updated @ git+https://projects.blender.org/infrastructur
|
||||
django[bcrypt]==4.2.13 ; python_version >= "3.8" and python_version < "4"
|
||||
django-compat==1.0.15 ; python_version >= "3.8" and python_version < "4"
|
||||
django-loginas==0.3.11 ; python_version >= "3.8" and python_version < "4"
|
||||
django-nacl-fields==4.1.0
|
||||
django-oauth-toolkit @ git+https://projects.blender.org/Oleg-Komarov/django-oauth-toolkit.git@0b056a99ca943771615b859f48aaff0e12357f22 ; python_version >= "3.8" and python_version < "4"
|
||||
django-otp==1.5.1
|
||||
django-otp-agents==1.0.1
|
||||
@ -41,6 +42,7 @@ pycparser==2.19 ; python_version >= "3.8" and python_version < "4"
|
||||
pygments==2.17.2 ; python_version >= "3.8" and python_version < "4"
|
||||
pyinstrument==4.6.0 ; python_version >= "3.8" and python_version < "4"
|
||||
pymdown-extensions==10.7 ; python_version >= "3.8" and python_version < "4"
|
||||
pynacl==1.5.0
|
||||
pypng==0.20220715.0
|
||||
pypugjs==5.9.12 ; python_version >= "3.8" and python_version < "4"
|
||||
python-dateutil==2.8.1 ; python_version >= "3.8" and python_version < "4"
|
||||
|
Loading…
Reference in New Issue
Block a user