diff --git a/.gitignore b/.gitignore index b6d98ff..f3d5cc3 100644 --- a/.gitignore +++ b/.gitignore @@ -104,3 +104,4 @@ venv.bak/ # mypy .mypy_cache/ +example/test_db diff --git a/CHANGELOG.md b/CHANGELOG.md index 9657b2d..a758b04 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,4 +1,13 @@ # Change Log +## 2.6.0 (dev) + * Adding Backup Recovery Codes (Recovery) as a method. + Thanks to @Spitfireap for work, and @peterthomassen for guidance. + * Added: `RECOVERY_ITERATION` to set the number of iteration when hashing recovery token + * Added: `MFA_ENFORCE_RECOVERY_METHOD` to enforce the user to enroll in the recovery code method once, they add any other method, + * Added: `MFA_ALWAYS_GO_TO_LAST_METHOD` to the settings which redirects the user automatically to the last used method when logging in + * Added: `MFA_RENAME_METHODS` to be able to rename the methods for the user. + * Fix: Alot of CSS fixes for the example application + ## 2.5.0 * Fixed: issue in the 'Authorize' button don't show on Firefox and Chrome on iOS. diff --git a/EXAMPLE.md b/EXAMPLE.md index b38b93a..d78afba 100644 --- a/EXAMPLE.md +++ b/EXAMPLE.md @@ -4,5 +4,15 @@ `virtualenv venv` 1. activate env `source venv/bin/activate` 1. install requirements `pip install -r requirements.txt` +1. cd to example project `cd example` 1. migrate `python manage.py migrate` -1. create super user 'python manage.py createsuperuser' \ No newline at end of file +1. create super user `python manage.py createsuperuser` +1. start the server `python manage.py runserver` + +# Notes for SSL + +To test FIDO2 you need to use HTTPS, after the above steps are done: + +1. stop the server +1. install requirements `pip install -r example-ssl-requirements.txt` +1. start the ssl server `python manage.py runsslserver` diff --git a/README.md b/README.md index 2953966..d584832 100644 --- a/README.md +++ b/README.md @@ -1,5 +1,5 @@ # django-mfa2 -A Django app that handles MFA, it supports TOTP, U2F, FIDO2 U2F (Web Authn), Email Tokens , and Trusted Devices +A Django app that handles MFA, it supports TOTP, U2F, FIDO2 U2F (Web Authn), Email Tokens , Trusted Devices and backup codes. ### Pip Stats [![PyPI version](https://badge.fury.io/py/django-mfa2.svg)](https://badge.fury.io/py/django-mfa2) @@ -66,8 +66,9 @@ Depends on `python manage.py collectstatic` 3. Add the following settings to your file - ```python - MFA_UNALLOWED_METHODS=() # Methods that shouldn't be allowed for the user + ```python + from django.conf.global_settings import PASSWORD_HASHERS as DEFAULT_PASSWORD_HASHERS #Preferably at the same place where you import your other modules + MFA_UNALLOWED_METHODS=() # Methods that shouldn't be allowed for the user e.g ('TOTP','U2F',) MFA_LOGIN_CALLBACK="" # A function that should be called by username to login the user in session MFA_RECHECK=True # Allow random rechecking of the user MFA_REDIRECT_AFTER_REGISTRATION="mfa_home" # Allows Changing the page after successful registeration @@ -75,15 +76,19 @@ Depends on MFA_RECHECK_MIN=10 # Minimum interval in seconds MFA_RECHECK_MAX=30 # Maximum in seconds MFA_QUICKLOGIN=True # Allow quick login for returning users by provide only their 2FA + MFA_ALWAYS_GO_TO_LAST_METHOD = False # Always redirect the user to the last method used to save a click (Added in 2.6.0). + MFA_RENAME_METHODS={} #Rename the methods in a more user-friendly way e.g {"RECOVERY":"Backup Codes"} (Added in 2.6.0) MFA_HIDE_DISABLE=('FIDO2',) # Can the user disable his key (Added in 1.2.0). MFA_OWNED_BY_ENTERPRISE = FALSE # Who owns security keys + PASSWORD_HASHERS = DEFAULT_PASSWORD_HASHERS # Comment if PASSWORD_HASHER already set in your settings.py + PASSWORD_HASHERS += ['mfa.recovery.Hash'] + RECOVERY_ITERATION = 350000 #Number of iteration for recovery code, higher is more secure, but uses more resources for generation and check... TOKEN_ISSUER_NAME="PROJECT_NAME" #TOTP Issuer name U2F_APPID="https://localhost" #URL For U2F - FIDO_SERVER_ID=u"localehost" # Server rp id for FIDO2, it the full domain of your project + FIDO_SERVER_ID=u"localehost" # Server rp id for FIDO2, it is the full domain of your project FIDO_SERVER_NAME=u"PROJECT_NAME" - FIDO_LOGIN_URL=BASE_URL ``` **Method Names** * U2F @@ -91,12 +96,15 @@ Depends on * TOTP * Trusted_Devices * Email + * RECOVERY **Notes**: * Starting version 1.1, ~~FIDO_LOGIN_URL~~ isn't required for FIDO2 anymore. * Starting version 1.7.0, Key owners can be specified. * Starting version 2.2.0 * Added: `MFA_SUCCESS_REGISTRATION_MSG` & `MFA_REDIRECT_AFTER_REGISTRATION` + Start version 2.6.0 + * Added: `MFA_ALWAYS_GO_TO_LAST_METHOD`, `MFA_RENAME_METHODS`, `MFA_ENFORCE_RECOVERY_METHOD` & `RECOVERY_ITERATION` 4. Break your login function Usually your login function will check for username and password, log the user in if the username and password are correct and create the user session, to support mfa, this has to change @@ -136,7 +144,7 @@ Depends on ```
  • Security
  • ``` -For Example, See 'example' app +For Example, See 'example' app and look at EXAMPLE.md to see how to set it up. # Going Passwordless diff --git a/example/example-ssl-requirements.txt b/example/example-ssl-requirements.txt new file mode 100644 index 0000000..373b09d --- /dev/null +++ b/example/example-ssl-requirements.txt @@ -0,0 +1 @@ +django-sslserver diff --git a/example/example/settings.py b/example/example/settings.py index 6c1b772..a341a6c 100644 --- a/example/example/settings.py +++ b/example/example/settings.py @@ -11,6 +11,7 @@ """ import os +from django.conf.global_settings import PASSWORD_HASHERS as DEFAULT_PASSWORD_HASHERS # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) @@ -142,9 +143,14 @@ MFA_HIDE_DISABLE=('',) # Can the user disable his key (Added in 1.2.0). MFA_REDIRECT_AFTER_REGISTRATION="registered" MFA_SUCCESS_REGISTRATION_MSG="Go to Home" - +MFA_ALWAYS_GO_TO_LAST_METHOD = True +MFA_ENFORCE_RECOVERY_METHOD = True +MFA_RENAME_METHODS = {"RECOVERY":"Backup Codes","FIDO2":"Biometric Authentication"} +PASSWORD_HASHERS = DEFAULT_PASSWORD_HASHERS #Comment if PASSWORD_HASHER already set +PASSWORD_HASHERS += ['mfa.recovery.Hash'] +RECOVERY_ITERATION = 1 #Number of iteration for recovery code, higher is more secure, but uses more resources for generation and check... TOKEN_ISSUER_NAME="PROJECT_NAME" #TOTP Issuer name -U2F_APPID="https://localhost" #URL For U2F +U2F_APPID="https://localhost:9000" #URL For U2F FIDO_SERVER_ID="localhost" # Server rp id for FIDO2, it the full domain of your project FIDO_SERVER_NAME="TestApp" diff --git a/example/example/templates/base.html b/example/example/templates/base.html index e5b1a6e..be5fdb6 100644 --- a/example/example/templates/base.html +++ b/example/example/templates/base.html @@ -10,7 +10,7 @@ - SB Admin - Blank Page + Django-mfa2 Example diff --git a/example/requiremnts.txt b/example/requiremnts.txt deleted file mode 100644 index ee8e548..0000000 --- a/example/requiremnts.txt +++ /dev/null @@ -1,2 +0,0 @@ -django >= 2.2 -django_ssl diff --git a/mfa/Email.py b/mfa/Email.py index 010d6d5..047ec7a 100644 --- a/mfa/Email.py +++ b/mfa/Email.py @@ -34,10 +34,16 @@ def start(request): from django.core.urlresolvers import reverse except: from django.urls import reverse - return HttpResponseRedirect(reverse(getattr(settings,'MFA_REDIRECT_AFTER_REGISTRATION','mfa_home'))) + if getattr(settings, 'MFA_ENFORCE_RECOVERY_METHOD', False) and not User_Keys.objects.filter( + key_type="RECOVERY", username=request.user.username).exists(): + request.session["mfa_reg"] = {"method": "Email", + "name": getattr(settings, "MFA_RENAME_METHODS", {}).get("Email", "Email")} + else: + return HttpResponseRedirect(reverse(getattr(settings,'MFA_REDIRECT_AFTER_REGISTRATION','mfa_home'))) context["invalid"] = True else: request.session["email_secret"] = str(randint(0,100000)) #generate a random integer + if sendEmail(request, request.user.username, request.session["email_secret"]): context["sent"] = True return render(request,"Email/Add.html", context) diff --git a/mfa/FIDO2.py b/mfa/FIDO2.py index dcdf9f2..22eae99 100644 --- a/mfa/FIDO2.py +++ b/mfa/FIDO2.py @@ -66,7 +66,11 @@ def complete_reg(request): uk.owned_by_enterprise = getattr(settings, "MFA_OWNED_BY_ENTERPRISE", False) uk.key_type = "FIDO2" uk.save() - return HttpResponse(simplejson.dumps({'status': 'OK'})) + if getattr(settings, 'MFA_ENFORCE_RECOVERY_METHOD', False) and not User_Keys.objects.filter(key_type = "RECOVERY", username=request.user.username).exists(): + request.session["mfa_reg"] = {"method":"FIDO2","name": getattr(settings, "MFA_RENAME_METHODS", {}).get("FIDO2", "FIDO2")} + return HttpResponse(simplejson.dumps({'status': 'RECOVERY'})) + else: + return HttpResponse(simplejson.dumps({'status': 'OK'})) except Exception as exp: import traceback print(traceback.format_exc()) @@ -79,9 +83,11 @@ def complete_reg(request): def start(request): - """Start Registeration a new FIDO Token""" + """Start Registration a new FIDO Token""" context = csrf(request) context.update(get_redirect_url()) + context["method"] = {"name":getattr(settings,"MFA_RENAME_METHODS",{}).get("FIDO2","FIDO2 Security Key")} + context["RECOVERY_METHOD"]=getattr(settings,"MFA_RENAME_METHODS",{}).get("RECOVERY","Recovery codes") return render(request, "FIDO2/Add.html", context) @@ -137,7 +143,7 @@ def authenticate_complete(request): except: pass return HttpResponse(simplejson.dumps({'status': "ERR", - "message": excep.message}), + "message": str(excep)}), content_type = "application/json") if request.session.get("mfa_recheck", False): diff --git a/mfa/U2F.py b/mfa/U2F.py index 0eb04f0..bf247cc 100644 --- a/mfa/U2F.py +++ b/mfa/U2F.py @@ -52,25 +52,29 @@ def validate(request,username): challenge = request.session.pop('_u2f_challenge_') device, c, t = complete_authentication(challenge, data, [settings.U2F_APPID]) + try: + key=User_Keys.objects.get(username=username,properties__icontains='"publicKey": "%s"'%device["publicKey"]) + key.last_used=timezone.now() + key.save() + mfa = {"verified": True, "method": "U2F","id":key.id} + if getattr(settings, "MFA_RECHECK", False): + mfa["next_check"] = datetime.datetime.timestamp((datetime.datetime.now() + + datetime.timedelta( + seconds=random.randint(settings.MFA_RECHECK_MIN, settings.MFA_RECHECK_MAX)))) + request.session["mfa"] = mfa + return True + except: + return False + - key=User_Keys.objects.get(username=username,properties__shas="$.device.publicKey=%s"%device["publicKey"]) - key.last_used=timezone.now() - key.save() - mfa = {"verified": True, "method": "U2F","id":key.id} - if getattr(settings, "MFA_RECHECK", False): - mfa["next_check"] = datetime.datetime.timestamp((datetime.datetime.now() - + datetime.timedelta( - seconds=random.randint(settings.MFA_RECHECK_MIN, settings.MFA_RECHECK_MAX)))) - request.session["mfa"] = mfa - return True def auth(request): context=csrf(request) s=sign(request.session["base_username"]) request.session["_u2f_challenge_"]=s[0] context["token"]=s[1] - - return render(request,"U2F/Auth.html") + context["method"] = {"name": getattr(settings, "MFA_RENAME_METHODS", {}).get("U2F", "Classical Security Key")} + return render(request,"U2F/Auth.html",context) def start(request): enroll = begin_registration(settings.U2F_APPID, []) @@ -78,6 +82,8 @@ def start(request): context=csrf(request) context["token"]=simplejson.dumps(enroll.data_for_client) context.update(get_redirect_url()) + context["method"] = {"name": getattr(settings, "MFA_RENAME_METHODS", {}).get("U2F", "Classical Security Key")} + context["RECOVERY_METHOD"] = getattr(settings, "MFA_RENAME_METHODS", {}).get("RECOVERY", "Recovery codes") return render(request,"U2F/Add.html",context) @@ -98,6 +104,11 @@ def bind(request): uk.properties = {"device":simplejson.loads(device.json),"cert":cert_hash} uk.key_type = "U2F" uk.save() + if getattr(settings, 'MFA_ENFORCE_RECOVERY_METHOD', False) and not User_Keys.objects.filter(key_type="RECOVERY", + username=request.user.username).exists(): + request.session["mfa_reg"] = {"method": "U2F", + "name": getattr(settings, "MFA_RENAME_METHODS", {}).get("U2F", "Classical Security Key")} + return HttpResponse('RECOVERY') return HttpResponse("OK") def sign(username): diff --git a/mfa/recovery.py b/mfa/recovery.py new file mode 100644 index 0000000..f2c1547 --- /dev/null +++ b/mfa/recovery.py @@ -0,0 +1,122 @@ +from django.shortcuts import render +from django.views.decorators.cache import never_cache +from django.template.context_processors import csrf +from django.contrib.auth.hashers import make_password, PBKDF2PasswordHasher +from django.http import HttpResponse +from .Common import get_redirect_url +from .models import * +import simplejson +import random +import string +import datetime +from django.utils import timezone + +USER_FRIENDLY_NAME = "Recovery Codes" + +class Hash(PBKDF2PasswordHasher): + algorithm = 'pbkdf2_sha256_custom' + iterations = getattr(settings,"RECOVERY_ITERATION",1) + +def delTokens(request): + #Only when all MFA have been deactivated, or to generate new ! + #We iterate only to clean if any error happend and multiple entry of RECOVERY created for one user + for key in User_Keys.objects.filter(username=request.user.username, key_type = "RECOVERY"): + if key.username == request.user.username: + key.delete() + +def randomGen(n): + return ''.join(random.choice(string.ascii_uppercase + string.ascii_lowercase + string.digits) for _ in range(n)) + +@never_cache +def genTokens(request): + #Delete old ones + delTokens(request) + #Then generate new one + salt = randomGen(15) + hashedKeys = [] + clearKeys = [] + for i in range(5): + token = randomGen(5) + "-" + randomGen(5) + hashedToken = make_password(token, salt, 'pbkdf2_sha256_custom') + hashedKeys.append(hashedToken) + clearKeys.append(token) + uk=User_Keys() + + uk.username = request.user.username + uk.properties={"secret_keys":hashedKeys, "salt":salt} + uk.key_type="RECOVERY" + uk.enabled = True + uk.save() + return HttpResponse(simplejson.dumps({"keys":clearKeys})) + + +def verify_login(request, username, token): + for key in User_Keys.objects.filter(username=username, key_type = "RECOVERY"): + secret_keys = key.properties["secret_keys"] + salt = key.properties["salt"] + hashedToken = make_password(token, salt, "pbkdf2_sha256_custom") + for i,token in enumerate(secret_keys): + if hashedToken == token: + secret_keys.pop(i) + key.properties["secret_keys"] = secret_keys + key.last_used= timezone.now() + key.save() + return [True, key.id, len(secret_keys) == 0] + return [False] + +def getTokenLeft(request): + uk = User_Keys.objects.filter(username=request.user.username, key_type = "RECOVERY") + keyLeft=0 + for key in uk: + keyLeft += len(key.properties["secret_keys"]) + return HttpResponse(simplejson.dumps({"left":keyLeft})) + +def recheck(request): + context = csrf(request) + context["mode"]="recheck" + if request.method == "POST": + if verify_login(request,request.user.username, token=request.POST["recovery"])[0]: + import time + request.session["mfa"]["rechecked_at"] = time.time() + return HttpResponse(simplejson.dumps({"recheck": True}), content_type="application/json") + else: + return HttpResponse(simplejson.dumps({"recheck": False}), content_type="application/json") + return render(request,"RECOVERY/recheck.html", context) + +@never_cache +def auth(request): + from .views import login + context=csrf(request) + if request.method=="POST": + tokenLength = len(request.POST["recovery"]) + if tokenLength == 11 and "RECOVERY" not in settings.MFA_UNALLOWED_METHODS: + #Backup code check + resBackup=verify_login(request, request.session["base_username"], token=request.POST["recovery"]) + if resBackup[0]: + mfa = {"verified": True, "method": "RECOVERY","id":resBackup[1], "lastBackup":resBackup[2]} + # if getattr(settings, "MFA_RECHECK", False): + # mfa["next_check"] = datetime.datetime.timestamp((datetime.datetime.now() + # + datetime.timedelta( + # seconds=random.randint(settings.MFA_RECHECK_MIN, settings.MFA_RECHECK_MAX)))) + request.session["mfa"] = mfa + if resBackup[2]: + #If the last bakup code has just been used, we return a response insead of redirecting to login + context["lastBackup"] = True + return render(request,"RECOVERY/Auth.html", context) + return login(request) + context["invalid"]=True + + elif request.method=="GET": + mfa = request.session.get("mfa") + if mfa and mfa["verified"] and mfa["lastBackup"]: + return login(request) + + return render(request,"RECOVERY/Auth.html", context) + +@never_cache +def start(request): + """Start Managing recovery tokens""" + context = get_redirect_url() + if "mfa_reg" in request.session: + context["mfa_redirect"] = request.session["mfa_reg"]["name"] + return render(request,"RECOVERY/Add.html",context) \ No newline at end of file diff --git a/mfa/templates/FIDO2/Add.html b/mfa/templates/FIDO2/Add.html index fc11d37..2b8071d 100644 --- a/mfa/templates/FIDO2/Add.html +++ b/mfa/templates/FIDO2/Add.html @@ -32,9 +32,14 @@ }).then(function (res) { if (res["status"] =='OK') - $("#res").html("
    Registered Successfully, {{reg_success_msg}}
    ") - else - $("#res").html("
    Registration Failed as " + res["message"] + ", try again or Go to Security Home
    ") + $("#res").html("
    Registered Successfully, {{reg_success_msg}}
    ") + else if (res['status'] = "RECOVERY") + { + setTimeout(function (){location.href="{% url 'manage_recovery_codes' %}"},2500) + $("#res").html("
    Registered Successfully, but redirecting to {{ RECOVERY_METHOD }} method
    ") + } + else + $("#res").html("
    Registration Failed as " + res["message"] + ", try again or Go to Security Home
    ") }, function(reason) { @@ -61,7 +66,7 @@
    - FIDO2 Security Key + Adding a New {{ method.name }}
    diff --git a/mfa/templates/FIDO2/recheck.html b/mfa/templates/FIDO2/recheck.html index 0b128bf..c44db3a 100644 --- a/mfa/templates/FIDO2/recheck.html +++ b/mfa/templates/FIDO2/recheck.html @@ -3,7 +3,7 @@
    -
    +
    Security Key @@ -35,10 +35,10 @@
    -
    +
    {% if request.session.mfa_methods|length > 1 %} - Select Another Method + Select Another Method {% endif %}
    diff --git a/mfa/templates/MFA.html b/mfa/templates/MFA.html index 4940ad8..afcc59d 100644 --- a/mfa/templates/MFA.html +++ b/mfa/templates/MFA.html @@ -45,31 +45,31 @@
    -
    +
    -
    +

    @@ -82,28 +82,42 @@ - {% for key in keys %} - + {% if keys %} + {% for key in keys %} + - - - - - - {% if key.key_type in HIDE_DISABLE %} - - {% else %} - - {% endif %} - + + + + + + {% if key.key_type in HIDE_DISABLE %} + + {% else %} + {% endif %} - - {% empty %} + + {% endif %} + + {% endfor %} + {% if "RECOVERY" not in UNALLOWED_AUTHEN_METHODS %} + + + + + + + + + + + {% endif %} + {% else %} - {% endfor %} + {% endif %}
    Status Delete
    {{ key.key_type }}{{ key.added_on }}{{ key.expires }}{% if key.device %}{{ key.device }}{% endif %}{{ key.last_used }}{% if key.enabled %}On{% else %} Off{% endif %}{% if key.key_type in HIDE_DISABLE %} - ---- - {% else %} - {{ key.name }}{{ key.added_on }}{% if key.expires %}{{ key.expires }}{% else %}N/A{% endif %}{% if key.device %}{{ key.device }}{% endif %}{% if key.last_used %}{{ key.last_used }}{% else %}Never{% endif %}{% if key.enabled %}On{% else %} Off{% endif %}
    {% if key.key_type in HIDE_DISABLE %} + ---- + {% else %} +
    {{ recovery.name }}{{ recovery.added_on }}N/AN/A{% if recovery.last_used %}{{ recovery.last_used }}{% else %}Never{% endif %}On
    You didn't have any keys yet.
    diff --git a/mfa/templates/RECOVERY/Add.html b/mfa/templates/RECOVERY/Add.html new file mode 100644 index 0000000..d337ada --- /dev/null +++ b/mfa/templates/RECOVERY/Add.html @@ -0,0 +1,134 @@ + +{% extends "base.html" %} +{% load static %} +{% block head %} + + + + +{% endblock %} +{% block content %} +
    +
    +
    +
    + +
    + +

    Recovery Codes List

    + +
    + +
    + +
    +
    +
    +
    + +
    + + + +
    + + +
    +
    +
    +{% include "modal.html" %} +{% endblock %} diff --git a/mfa/templates/RECOVERY/Auth.html b/mfa/templates/RECOVERY/Auth.html new file mode 100644 index 0000000..82b80a3 --- /dev/null +++ b/mfa/templates/RECOVERY/Auth.html @@ -0,0 +1,14 @@ +{% extends "mfa_auth_base.html" %} +{% block head %} + +{% endblock %} +{% block content %} +
    +
    +{% include "RECOVERY/recheck.html" with mode='auth' %} + + {% endblock %} diff --git a/mfa/templates/RECOVERY/recheck.html b/mfa/templates/RECOVERY/recheck.html new file mode 100644 index 0000000..501375f --- /dev/null +++ b/mfa/templates/RECOVERY/recheck.html @@ -0,0 +1,85 @@ + +
    +
    +
    +
    + Recovery code +
    +
    + +
    + + + {% csrf_token %} + {% if invalid %} +
    + Sorry, The provided code is not valid, or has already been used. +
    + {% endif %} + {% if quota %} +
    + {{ quota }} +
    + {% endif %} +
    +
    +
    +

    Enter the 11-digits on your authenticator. Or input a recovery code

    +
    +
    + +
    +
    +
    +
    + + + + + +
    +
    + +
    + + +
    +
    +
    +
    +
    +
    +
    + {% if request.session.mfa_methods|length > 1 %} + Select Another Method + {% endif %} +
    +
    +
    +
    +
    +
    +{% include "modal.html" %} \ No newline at end of file diff --git a/mfa/templates/TOTP/Add.html b/mfa/templates/TOTP/Add.html index 7bd2ce6..bd6c145 100644 --- a/mfa/templates/TOTP/Add.html +++ b/mfa/templates/TOTP/Add.html @@ -7,10 +7,22 @@ border: 1px solid #ccc; border-radius: 3px; padding: 15px; -} + } .row{ margin: 0px; } + .toolbtn { + border-radius: 7px; + cursor: pointer; + } + .toolbtn:hover { + background-color: gray; + transition: 0.2s; + } + .toolbtn:active { + background-color: green; + transition: 0.2s; + }
    @@ -40,7 +39,7 @@
    -

    Enter the 6-digits on your authenticator.

    +

    Enter the 6-digits on your authenticator

    @@ -58,8 +57,7 @@
    - -
    +
    @@ -76,3 +74,4 @@
    +{% include "modal.html" %} \ No newline at end of file diff --git a/mfa/templates/U2F/Add.html b/mfa/templates/U2F/Add.html index 0eefcd4..ae81563 100644 --- a/mfa/templates/U2F/Add.html +++ b/mfa/templates/U2F/Add.html @@ -13,7 +13,7 @@ {% endblock %} @@ -37,9 +46,11 @@

    +
    +
    -

    Adding Security Key

    +

    Adding {{ method.name}}

    Your secure Key should be flashing now, please press on button.

    diff --git a/mfa/templates/U2F/recheck.html b/mfa/templates/U2F/recheck.html index 5f47b44..a908ae8 100644 --- a/mfa/templates/U2F/recheck.html +++ b/mfa/templates/U2F/recheck.html @@ -4,7 +4,7 @@
    - Security Key + Verify your identity using {{ method.name }}
    diff --git a/mfa/templates/select_mfa_method.html b/mfa/templates/select_mfa_method.html index 0ee10f6..aa59acb 100644 --- a/mfa/templates/select_mfa_method.html +++ b/mfa/templates/select_mfa_method.html @@ -1,11 +1,10 @@ {% extends "mfa_auth_base.html" %} {% block content %} -

    -
    +
    Select Second Verification Method @@ -15,10 +14,11 @@ {% for method in request.session.mfa_methods %}
  • - {% if method == "TOTP" %}Authenticator App - {% elif method == "Email" %}Send OTP by Email - {% elif method == "U2F" %}Secure Key - {% elif method == "FIDO2" %}FIDO2 Secure Key + {% if method == "TOTP" %}{% if 'TOTP' in RENAME_METHODS %}{{ RENAME_METHODS.TOTP }}{% else %}Authenticator App{% endif %} + {% elif method == "Email" %}{% if 'Email' in RENAME_METHODS %}{{ RENAME_METHODS.Email }}{% else %}Send OTP by Email{% endif %} + {% elif method == "U2F" %}{% if 'U2F' in RENAME_METHODS %}{{ RENAME_METHODS.U2F }}{% else %}Secure Key{% endif %} + {% elif method == "FIDO2" %}{% if 'FIDO2' in RENAME_METHODS %}{{ RENAME_METHODS.FIDO2 }}{% else %}FIDO2 Secure Key{% endif %} + {% elif method == "RECOVERY" %}{% if 'RECOVERY' in RENAME_METHODS %}{{ RENAME_METHODS.RECOVERY }}{% else %}Recovery Code{% endif %} {% endif %}
  • {% endfor %} diff --git a/mfa/totp.py b/mfa/totp.py index 76aa810..4cf099c 100644 --- a/mfa/totp.py +++ b/mfa/totp.py @@ -5,13 +5,14 @@ from .models import * from django.template.context_processors import csrf import simplejson -from django.template.context import RequestContext from django.conf import settings import pyotp from .views import login import datetime from django.utils import timezone import random + + def verify_login(request,username,token): for key in User_Keys.objects.filter(username=username,key_type = "TOTP"): totp = pyotp.TOTP(key.properties["secret_key"]) @@ -25,7 +26,7 @@ def recheck(request): context = csrf(request) context["mode"]="recheck" if request.method == "POST": - if verify_login(request,request.user.username, token=request.POST["otp"]): + if verify_login(request,request.user.username, token=request.POST["otp"])[0]: import time request.session["mfa"]["rechecked_at"] = time.time() return HttpResponse(simplejson.dumps({"recheck": True}), content_type="application/json") @@ -37,15 +38,18 @@ def recheck(request): def auth(request): context=csrf(request) if request.method=="POST": - res=verify_login(request,request.session["base_username"],token = request.POST["otp"]) - if res[0]: - mfa = {"verified": True, "method": "TOTP","id":res[1]} - if getattr(settings, "MFA_RECHECK", False): - mfa["next_check"] = datetime.datetime.timestamp((datetime.datetime.now() - + datetime.timedelta( - seconds=random.randint(settings.MFA_RECHECK_MIN, settings.MFA_RECHECK_MAX)))) - request.session["mfa"] = mfa - return login(request) + tokenLength = len(request.POST["otp"]) + if tokenLength == 6: + #TOTO code check + res=verify_login(request,request.session["base_username"],token = request.POST["otp"]) + if res[0]: + mfa = {"verified": True, "method": "TOTP","id":res[1]} + if getattr(settings, "MFA_RECHECK", False): + mfa["next_check"] = datetime.datetime.timestamp((datetime.datetime.now() + + datetime.timedelta( + seconds=random.randint(settings.MFA_RECHECK_MIN, settings.MFA_RECHECK_MAX)))) + request.session["mfa"] = mfa + return login(request) context["invalid"]=True return render(request,"TOTP/Auth.html", context) @@ -68,10 +72,19 @@ def verify(request): #uk.name="Authenticatior #%s"%User_Keys.objects.filter(username=user.username,type="TOTP") uk.key_type="TOTP" uk.save() - return HttpResponse("Success") + if getattr(settings, 'MFA_ENFORCE_RECOVERY_METHOD', False) and not User_Keys.objects.filter(key_type="RECOVERY", + username=request.user.username).exists(): + request.session["mfa_reg"] = {"method": "TOTP", + "name": getattr(settings, "MFA_RENAME_METHODS", {}).get("TOTP", "TOTP")} + return HttpResponse("RECOVERY") + else: + return HttpResponse("Success") else: return HttpResponse("Error") @never_cache def start(request): """Start Adding Time One Time Password (TOTP)""" - return render(request,"TOTP/Add.html",get_redirect_url()) + context = get_redirect_url() + context["RECOVERY_METHOD"] = getattr(settings, "MFA_RENAME_METHODS", {}).get("RECOVERY", "Recovery codes") + context["method"] = {"name":getattr(settings,"MFA_RENAME_METHODS",{}).get("TOTP","Authenticator")} + return render(request,"TOTP/Add.html",context) diff --git a/mfa/urls.py b/mfa/urls.py index 90e9432..6d5e7dc 100644 --- a/mfa/urls.py +++ b/mfa/urls.py @@ -1,4 +1,4 @@ -from . import views,totp,U2F,TrustedDevice,helpers,FIDO2,Email +from . import views,totp,U2F,TrustedDevice,helpers,FIDO2,Email,recovery #app_name='mfa' try: @@ -12,6 +12,12 @@ url(r'totp/auth', totp.auth, name="totp_auth"), url(r'totp/recheck', totp.recheck, name="totp_recheck"), + url(r'recovery/start', recovery.start, name="manage_recovery_codes"), + url(r'recovery/getTokenLeft', recovery.getTokenLeft, name="get_recovery_token_left"), + url(r'recovery/genTokens', recovery.genTokens, name="regen_recovery_tokens"), + url(r'recovery/auth', recovery.auth, name="recovery_auth"), + url(r'recovery/recheck', recovery.recheck, name="recovery_recheck"), + url(r'email/start/', Email.start , name="start_email"), url(r'email/auth/', Email.auth , name="email_auth"), diff --git a/mfa/views.py b/mfa/views.py index 9039363..819dae5 100644 --- a/mfa/views.py +++ b/mfa/views.py @@ -1,3 +1,5 @@ +import importlib + from django.shortcuts import render from django.http import HttpResponse,HttpResponseRedirect from .models import * @@ -16,12 +18,16 @@ def index(request): keys=[] context={"keys":User_Keys.objects.filter(username=request.user.username),"UNALLOWED_AUTHEN_METHODS":settings.MFA_UNALLOWED_METHODS - ,"HIDE_DISABLE":getattr(settings,"MFA_HIDE_DISABLE",[])} + ,"HIDE_DISABLE":getattr(settings,"MFA_HIDE_DISABLE",[]),'RENAME_METHODS':getattr(settings,'MFA_RENAME_METHODS',{})} for k in context["keys"]: - if k.key_type =="Trusted Device" : + k.name = getattr(settings,'MFA_RENAME_METHODS',{}).get(k.key_type,k.key_type) + if k.key_type =="Trusted Device": setattr(k,"device",parse(k.properties.get("user_agent","-----"))) elif k.key_type == "FIDO2": setattr(k,"device",k.properties.get("type","----")) + elif k.key_type == "RECOVERY": + context["recovery"] = k + continue keys.append(k) context["keys"]=keys return render(request,"MFA.html",context) @@ -37,17 +43,23 @@ def verify(request,username): return login(request) methods.remove("Trusted Device") request.session["mfa_methods"] = methods + if len(methods)==1: return HttpResponseRedirect(reverse(methods[0].lower()+"_auth")) + if getattr(settings,"MFA_ALWAYS_GO_TO_LAST_METHOD",False): + keys = keys.exclude(last_used__isnull=True).order_by("last_used") + if keys.count()>0: + return HttpResponseRedirect(reverse(keys[0].key_type.lower() + "_auth")) return show_methods(request) def show_methods(request): - return render(request,"select_mfa_method.html", {}) + return render(request,"select_mfa_method.html", {'RENAME_METHODS':getattr(settings,'MFA_RENAME_METHODS',{})}) def reset_cookie(request): response=HttpResponseRedirect(settings.LOGIN_URL) response.delete_cookie("base_username") return response + def login(request): from django.contrib import auth from django.conf import settings diff --git a/requirements.txt b/requirements.txt index 3b3941a..ba3a23f 100644 --- a/requirements.txt +++ b/requirements.txt @@ -1,4 +1,4 @@ -django >= 2.0 +django >= 2.2 jsonfield simplejson pyotp @@ -6,5 +6,5 @@ python-u2flib-server ua-parser user-agents python-jose -fido2 == 0.9.1 +fido2 == 1.0.0 jsonLookup