Initial mfa support (for internal users) #93591

Merged
Oleg-Komarov merged 46 commits from mfa into main 2024-08-29 11:44:06 +02:00
12 changed files with 165 additions and 22 deletions
Showing only changes of commit 734de7e49c - Show all commits

View File

@ -13,11 +13,11 @@ from django.template import defaultfilters
from django.utils import timezone from django.utils import timezone
from django.utils.translation import gettext_lazy as _ from django.utils.translation import gettext_lazy as _
from django_otp.oath import TOTP from django_otp.oath import TOTP
from django_otp.plugins.otp_totp.models import TOTPDevice
from otp_agents.views import OTPTokenForm from otp_agents.views import OTPTokenForm
from .models import User, OAuth2Application from .models import User, OAuth2Application
from .recaptcha import check_recaptcha from .recaptcha import check_recaptcha
from mfa.models import EncryptedTOTPDevice
import bid_main.tasks import bid_main.tasks
log = logging.getLogger(__name__) log = logging.getLogger(__name__)
@ -492,7 +492,7 @@ class TotpMfaForm(forms.Form):
) )
key = forms.CharField(widget=forms.HiddenInput) key = forms.CharField(widget=forms.HiddenInput)
name = forms.CharField( name = forms.CharField(
max_length=TOTPDevice._meta.get_field('name').max_length, max_length=EncryptedTOTPDevice._meta.get_field('name').max_length,
widget=forms.TextInput( widget=forms.TextInput(
attrs={"placeholder": "device name (for your convenience)"}, attrs={"placeholder": "device name (for your convenience)"},
), ),
@ -518,7 +518,7 @@ class TotpMfaForm(forms.Form):
def save(self): def save(self):
key = self.cleaned_data.get('key') key = self.cleaned_data.get('key')
name = self.cleaned_data.get('name') 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 @classmethod
def sign(cls, user, key): def sign(cls, user, key):

View File

@ -15,9 +15,6 @@ from django.core.mail import send_mail
from django.db import models, transaction from django.db import models, transaction
from django.db.models import Q from django.db.models import Q
from django import urls 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.templatetags.static import static
from django.utils.deconstruct import deconstructible from django.utils.deconstruct import deconstructible
from django.utils import timezone from django.utils import timezone
@ -27,6 +24,7 @@ import user_agents
from . import fields from . import fields
from . import hashers from . import hashers
from mfa.models import EncryptedRecoveryDevice, EncryptedTOTPDevice, devices_for_user
import bid_main.file_utils import bid_main.file_utils
import bid_main.utils import bid_main.utils
@ -548,9 +546,9 @@ class User(AbstractBaseUser, PermissionsMixin):
def mfa_devices_per_category(self): def mfa_devices_per_category(self):
devices_per_category = defaultdict(list) devices_per_category = defaultdict(list)
for device in devices_for_user(self): for device in devices_for_user(self):
if isinstance(device, StaticDevice): if isinstance(device, EncryptedRecoveryDevice):
devices_per_category['recovery'].append(device) devices_per_category['recovery'].append(device)
if isinstance(device, TOTPDevice): if isinstance(device, EncryptedTOTPDevice):
devices_per_category['totp'].append(device) devices_per_category['totp'].append(device)
return devices_per_category return devices_per_category

View File

@ -51,7 +51,7 @@ Multi-factor Authentication Setup
{% with recovery=devices_per_category.recovery.0 %} {% with recovery=devices_per_category.recovery.0 %}
{% if recovery %} {% if recovery %}
<div class="mb-3"> <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 {{ code_count }} recovery code{{ code_count|pluralize }} remaining
{% if recovery_codes %} {% if recovery_codes %}
<a href="?display_recovery_codes=" class="btn">Hide</a> <a href="?display_recovery_codes=" class="btn">Hide</a>

View File

@ -9,15 +9,13 @@ from django.urls import reverse, reverse_lazy
from django.views.generic import TemplateView from django.views.generic import TemplateView
from django.views.generic.base import View from django.views.generic.base import View
from django.views.generic.edit import DeleteView, FormView from django.views.generic.edit import DeleteView, FormView
from django_otp import devices_for_user
from django_otp.models import Device 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 from django_otp.util import random_hex
import qrcode import qrcode
from . import mixins from . import mixins
from bid_main.forms import DisableMfaForm, TotpMfaForm from bid_main.forms import DisableMfaForm, TotpMfaForm
from mfa.models import EncryptedRecoveryDevice, EncryptedTOTPDevice, devices_for_user
class MfaView(mixins.MfaRequiredIfConfiguredMixin, TemplateView): class MfaView(mixins.MfaRequiredIfConfiguredMixin, TemplateView):
@ -34,7 +32,8 @@ class MfaView(mixins.MfaRequiredIfConfiguredMixin, TemplateView):
user_can_setup_recovery = False user_can_setup_recovery = False
devices_per_category = user.mfa_devices_per_category() devices_per_category = user.mfa_devices_per_category()
if self.request.GET.get('display_recovery_codes') and 'recovery' in 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'}: if devices_per_category.keys() - {'recovery'}:
user_can_setup_recovery = True user_can_setup_recovery = True
return { return {
@ -52,7 +51,7 @@ class DisableView(mixins.MfaRequiredMixin, FormView):
@transaction.atomic @transaction.atomic
def form_valid(self, form): 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() device.delete()
return super().form_valid(form) return super().form_valid(form)
@ -61,15 +60,17 @@ class GenerateRecoveryView(mixins.MfaRequiredIfConfiguredMixin, View):
@transaction.atomic @transaction.atomic
def post(self, request, *args, **kwargs): def post(self, request, *args, **kwargs):
user = self.request.user 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 # Forbid setting up recovery codes unless the user already has some other method
return HttpResponseBadRequest("can't setup recovery codes before other methods") return HttpResponseBadRequest("can't setup recovery codes before other methods")
user.staticdevice_set.all().delete() 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): for _ in range(10):
# https://pages.nist.gov/800-63-3/sp800-63b.html#5122-look-up-secret-verifiers # https://pages.nist.gov/800-63-3/sp800-63b.html#5122-look-up-secret-verifiers
# don't use less than 64 bits # 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') 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): def get_form(self, *args, **kwargs):
kwargs = self.get_form_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']['key'] = key
kwargs['initial']['signature'] = TotpMfaForm.sign(kwargs['user'], key) kwargs['initial']['signature'] = TotpMfaForm.sign(kwargs['user'], key)
return TotpMfaForm(**kwargs) return TotpMfaForm(**kwargs)
@ -101,7 +102,7 @@ class TotpView(mixins.MfaRequiredIfConfiguredMixin, FormView):
key = context['form'].initial['key'] key = context['form'].initial['key']
b32key = b32encode(unhexlify(key)).decode('utf-8') b32key = b32encode(unhexlify(key)).decode('utf-8')
context['manual_secret_key'] = b32key 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 context['config_url'] = device.config_url
image = qrcode.make( image = qrcode.make(
device.config_url, device.config_url,
@ -126,7 +127,7 @@ class DeleteDeviceView(mixins.MfaRequiredMixin, DeleteView):
for device in devices_for_user(self.request.user): for device in devices_for_user(self.request.user):
if ( if (
device.persistent_id != kwargs['persistent_id'] 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 # there are other non-recovery devices, it's fine to delete this one
return super().get(request, *args, **kwargs) return super().get(request, *args, **kwargs)

View File

@ -22,8 +22,6 @@ from django.views.decorators.cache import never_cache
from django.views.generic import TemplateView, FormView from django.views.generic import TemplateView, FormView
from django.views.generic.base import View from django.views.generic.base import View
from django.views.generic.edit import UpdateView from django.views.generic.edit import UpdateView
from django_otp import devices_for_user
from otp_agents.forms import OTPTokenForm
import loginas.utils import loginas.utils
import oauth2_provider.models as oauth2_models import oauth2_provider.models as oauth2_models
import otp_agents.views import otp_agents.views

View File

@ -36,9 +36,25 @@ PREFERRED_SCHEME = "https"
# Update this to something unique for your machine. # Update this to something unique for your machine.
SECRET_KEY = os.getenv('SECRET_KEY', 'default-dev-secret') 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! # SECURITY WARNING: don't run with debug turned on in production!
DEBUG = bool(os.getenv('DEBUG', False)) 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'] TESTING = sys.argv[1:2] == ['test']
ALLOWED_HOSTS = os.getenv('ALLOWED_HOSTS', 'id.local').split(',') ALLOWED_HOSTS = os.getenv('ALLOWED_HOSTS', 'id.local').split(',')
@ -65,10 +81,12 @@ INSTALLED_APPS = [
"sorl.thumbnail", "sorl.thumbnail",
"django_admin_select2", "django_admin_select2",
"loginas", "loginas",
"nacl_encrypted_fields",
"bid_main", "bid_main",
"bid_api", "bid_api",
"bid_addon_support", "bid_addon_support",
"background_task", "background_task",
"mfa",
] ]
MIDDLEWARE = [ MIDDLEWARE = [

0
mfa/__init__.py Normal file
View File

6
mfa/apps.py Normal file
View File

@ -0,0 +1,6 @@
from django.apps import AppConfig
class MfaConfig(AppConfig):
default_auto_field = 'django.db.models.BigAutoField'
name = "mfa"

View 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',
),
),
],
),
]

View File

50
mfa/models.py Normal file
View 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(),
]

View File

@ -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[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-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-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-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==1.5.1
django-otp-agents==1.0.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" pygments==2.17.2 ; python_version >= "3.8" and python_version < "4"
pyinstrument==4.6.0 ; 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" pymdown-extensions==10.7 ; python_version >= "3.8" and python_version < "4"
pynacl==1.5.0
pypng==0.20220715.0 pypng==0.20220715.0
pypugjs==5.9.12 ; python_version >= "3.8" and python_version < "4" 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" python-dateutil==2.8.1 ; python_version >= "3.8" and python_version < "4"