Compare commits
37 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
22b5d0884c | ||
|
|
9569b0cfcd | ||
|
|
1f3fca0f48 | ||
|
|
7c2958bebf | ||
|
|
d06f860611 | ||
|
|
ef3a5d4f40 | ||
|
|
9465042d7b | ||
|
|
479a87456b | ||
|
|
f9f2d8c787 | ||
|
|
3a9bfd79fa | ||
|
|
c7e1de79e1 | ||
|
|
dc9ac7895c | ||
|
|
82fd6f28bd | ||
|
|
9aafce4e00 | ||
|
|
f2fa28a2d4 | ||
|
|
c693007d62 | ||
|
|
e73bdef40a | ||
|
|
5ff14d29d4 | ||
|
|
166afeab36 | ||
|
|
171270adfb | ||
|
|
0fa8520e66 | ||
|
|
6ccaec59bd | ||
|
|
8c413083d5 | ||
|
|
eb2095e650 | ||
|
|
f89518e91d | ||
|
|
153be3a558 | ||
|
|
852c2d7e0c | ||
|
|
8fe3d4e496 | ||
|
|
263a5e2b8c | ||
|
|
2af838bfd3 | ||
|
|
ce6a224818 | ||
|
|
5e699aa66a | ||
|
|
bed70d7c22 | ||
|
|
ad4ee7f4d2 | ||
|
|
7efd3ccc38 | ||
|
|
6efd643022 | ||
|
|
b199c86993 |
71
README.md
71
README.md
@@ -1,12 +1,21 @@
|
|||||||
# django-mfa2
|
# 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 , and Trusted Devices
|
||||||
|
|
||||||
|
[](https://badge.fury.io/py/django-mfa2)
|
||||||
|
|
||||||
For FIDO2, both security keys and android-safetynet are supported.
|
Web Authencation API (WebAuthn) is state-of-the art techology that is expected to replace passwords.
|
||||||
|
|
||||||
|

|
||||||
|
|
||||||
|
For FIDO2, **security keys**, **Windows Hello**, **Apple's Touch ID (Chrome)** and **android-safetynet** are supported.
|
||||||
|
|
||||||
|
In English :), It allows you to verify the user by security keys on PC, Laptops, Windows Hello (Fingerprint, PIN) on Windows 10 Build 1903 (May 2019 Update) Touch ID on Macbooks (Chrome) and Fingerprint/PIN on Andriod Phones.
|
||||||
|
|
||||||
Trusted device is a mode for the user to add a device that doesn't support security keys like iOS and andriod without fingerprints or NFC.
|
Trusted device is a mode for the user to add a device that doesn't support security keys like iOS and andriod without fingerprints or NFC.
|
||||||
|
|
||||||
`**Note**: U2F and FIDO2 can only be served under secure context (https)`
|
**Note**: `U2F and FIDO2 can only be served under secure context (https)`
|
||||||
|
|
||||||
|
Package tested with Django 1.8, Django 2.1 on Python 2.7 and Python 3.5+ but it was not checked with any version in between but open for issues.
|
||||||
|
|
||||||
Depends on
|
Depends on
|
||||||
|
|
||||||
@@ -27,6 +36,8 @@ Depends on
|
|||||||
'mfa',
|
'mfa',
|
||||||
'......')
|
'......')
|
||||||
```
|
```
|
||||||
|
1. Collect Static Files
|
||||||
|
`python manage.py collectstatic`
|
||||||
1. Add the following settings to your file
|
1. Add the following settings to your file
|
||||||
|
|
||||||
```python
|
```python
|
||||||
@@ -35,13 +46,14 @@ Depends on
|
|||||||
MFA_RECHECK=True # Allow random rechecking of the user
|
MFA_RECHECK=True # Allow random rechecking of the user
|
||||||
MFA_RECHECK_MIN=10 # Minimum interval in seconds
|
MFA_RECHECK_MIN=10 # Minimum interval in seconds
|
||||||
MFA_RECHECK_MAX=30 # Maximum in seconds
|
MFA_RECHECK_MAX=30 # Maximum in seconds
|
||||||
MFA_QUICKLOGIN=True # Allow quick login for returning users by provide only their 2FA
|
MFA_QUICKLOGIN=True # Allow quick login for returning users by provide only their 2FA
|
||||||
|
MFA_HIDE_DISABLE=('FIDO2',) # Can the user disable his key (Added in 1.2.0).
|
||||||
|
|
||||||
TOKEN_ISSUER_NAME="MDL" #TOTP Issuer name
|
TOKEN_ISSUER_NAME="PROJECT_NAME" #TOTP Issuer name
|
||||||
|
|
||||||
U2F_APPID="https://localhost" #URL For U2F
|
U2F_APPID="https://localhost" #URL For U2F
|
||||||
FIDO_SERVER_ID=u"localhost" # Server rp id for FIDO2
|
FIDO_SERVER_ID=u"localehost" # Server rp id for FIDO2, it the full domain of your project
|
||||||
FIDO_SERVER_NAME=u"MDL"
|
FIDO_SERVER_NAME=u"PROJECT_NAME"
|
||||||
FIDO_LOGIN_URL=BASE_URL
|
FIDO_LOGIN_URL=BASE_URL
|
||||||
```
|
```
|
||||||
**Method Names**
|
**Method Names**
|
||||||
@@ -51,6 +63,8 @@ Depends on
|
|||||||
* Trusted_Devices
|
* Trusted_Devices
|
||||||
* Email
|
* Email
|
||||||
|
|
||||||
|
**Note**: Starting version 1.1, ~~FIDO_LOGIN_URL~~ isn't required for FIDO2 anymore.
|
||||||
|
|
||||||
1. Break your login function
|
1. 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
|
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
|
||||||
@@ -77,7 +91,7 @@ Depends on
|
|||||||
import mfa.TrustedDevice
|
import mfa.TrustedDevice
|
||||||
urls_patterns= [
|
urls_patterns= [
|
||||||
'...',
|
'...',
|
||||||
url(r'^mfa/', include(mfa.urls)),
|
url(r'^mfa/', include('mfa.urls')),
|
||||||
url(r'devices/add$', mfa.TrustedDevice.add,name="mfa_add_new_trusted_device"), # This short link to add new trusted device
|
url(r'devices/add$', mfa.TrustedDevice.add,name="mfa_add_new_trusted_device"), # This short link to add new trusted device
|
||||||
'....',
|
'....',
|
||||||
]
|
]
|
||||||
@@ -87,6 +101,47 @@ Depends on
|
|||||||
If you will use Email Token method, then you have to provide template named `mfa_email_token_template.html` that will content the format of the email with parameter named `user` and `otp`.
|
If you will use Email Token method, then you have to provide template named `mfa_email_token_template.html` that will content the format of the email with parameter named `user` and `otp`.
|
||||||
1. To match the look and feel of your project, MFA includes `base.html` but it needs blocks named `head` & `content` to added its content to it.
|
1. To match the look and feel of your project, MFA includes `base.html` but it needs blocks named `head` & `content` to added its content to it.
|
||||||
1. Somewhere in your app, add a link to 'mfa_home'
|
1. Somewhere in your app, add a link to 'mfa_home'
|
||||||
```<l><a href="{% url 'mfa_home' %}">Security</a> </l>```
|
```<li><a href="{% url 'mfa_home' %}">Security</a> </li>```
|
||||||
|
|
||||||
For Example, See https://github.com/mkalioby/AutoDeploy/commit/5f1d94b1804e0aa33c79e9e8530ce849d9eb78cc in AutDeploy Project
|
For Example, See https://github.com/mkalioby/AutoDeploy/commit/5f1d94b1804e0aa33c79e9e8530ce849d9eb78cc in AutDeploy Project
|
||||||
|
|
||||||
|
# Going Passwordless
|
||||||
|
|
||||||
|
To be able to go passwordless for returning users, create a cookie named 'base_username' containing username as shown in snippet below
|
||||||
|
```python
|
||||||
|
response = render(request, 'Dashboard.html', context))
|
||||||
|
if request.session.get("mfa",{}).get("verified",False) and getattr(settings,"MFA_QUICKLOGIN",False):
|
||||||
|
if request.session["mfa"]["method"]!="Trusted Device":
|
||||||
|
response.set_cookie("base_username", request.user.username, path="/",max_age = 15*24*60*60)
|
||||||
|
return response
|
||||||
|
```
|
||||||
|
|
||||||
|
Second, update the GET part of your login view
|
||||||
|
```python
|
||||||
|
if "mfa" in settings.INSTALLED_APPS and getattr(settings,"MFA_QUICKLOGIN",False) and request.COOKIES.get('base_username'):
|
||||||
|
username=request.COOKIES.get('base_username')
|
||||||
|
from mfa.helpers import has_mfa
|
||||||
|
res = has_mfa(username = username,request=request,)
|
||||||
|
if res: return res
|
||||||
|
## continue and return the form.
|
||||||
|
```
|
||||||
|
# Checking MFA on Client Side
|
||||||
|
|
||||||
|
Sometimes you like to verify that the user is still there so simple you can ask django-mfa2 to check that for you
|
||||||
|
|
||||||
|
```html
|
||||||
|
{% include 'mfa_check.html' %}
|
||||||
|
```
|
||||||
|
````js
|
||||||
|
function success_func() {
|
||||||
|
//logic if mfa check succeeds
|
||||||
|
}
|
||||||
|
function fail_func() {
|
||||||
|
//logic if mfa check fails
|
||||||
|
}
|
||||||
|
function some_func() {
|
||||||
|
recheck_mfa(success_func,fail_func,MUST_BE_MFA)
|
||||||
|
//MUST_BE_MFA true or false, if the user must has with MFA
|
||||||
|
}
|
||||||
|
|
||||||
|
````
|
||||||
|
|||||||
23
docs/change_login.md
Normal file
23
docs/change_login.md
Normal file
@@ -0,0 +1,23 @@
|
|||||||
|
# Change of login function
|
||||||
|
|
||||||
|
## 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
|
||||||
|
|
||||||
|
* authenticate the user
|
||||||
|
* if username and password are correct , check if the user has mfa or not
|
||||||
|
* if user has mfa then redirect to mfa page
|
||||||
|
* if user doesn't have mfa then call your function to create the user session
|
||||||
|
|
||||||
|
<code>
|
||||||
|
def login(request): # this function handles the login form POST
|
||||||
|
user = auth.authenticate(username=username, password=password)
|
||||||
|
if user is not None: # if the user object exist
|
||||||
|
from mfa.helpers import has_mfa
|
||||||
|
res = has_mfa(username = username,request=request) # has_mfa returns false or HttpResponseRedirect
|
||||||
|
if res:
|
||||||
|
return res
|
||||||
|
return log_user_in(request,username=user.username)
|
||||||
|
#log_user_in is a function that handles creatung user session, it should be in the setting file as MFA_CALLBACK
|
||||||
|
</code>
|
||||||
|
|
||||||
36
docs/index.md
Normal file
36
docs/index.md
Normal file
@@ -0,0 +1,36 @@
|
|||||||
|
# django-mfa2
|
||||||
|
A Django app that handles MFA, it supports TOTP, U2F, FIDO2 U2F (Web Authn), Email Tokens , and Trusted Devices
|
||||||
|
|
||||||
|
[](https://badge.fury.io/py/django-mfa2)
|
||||||
|
|
||||||
|
Web Authencation API (WebAuthn) is state-of-the art techology that is expected to replace passwords.
|
||||||
|
|
||||||
|

|
||||||
|
|
||||||
|
For FIDO2, both security keys and android-safetynet are supported.
|
||||||
|
|
||||||
|
In English :), It allows you to verify the user by security keys on PC, Laptops and Fingerprint/PIN on Andriod Phones.
|
||||||
|
|
||||||
|
Trusted device is a mode for the user to add a device that doesn't support security keys like iOS and andriod without fingerprints or NFC.
|
||||||
|
|
||||||
|
**Note**: `U2F and FIDO2 can only be served under secure context (https)`
|
||||||
|
|
||||||
|
Package tested with Django 1.8, Django 2.1 on Python 2.7 and Python 3.5+ but it was not checked with any version in between but open for issues.
|
||||||
|
|
||||||
|
Depends on
|
||||||
|
|
||||||
|
* pyotp
|
||||||
|
* python-u2flib-server
|
||||||
|
* ua-parser
|
||||||
|
* user-agents
|
||||||
|
* python-jose
|
||||||
|
* fido2==0.5
|
||||||
|
|
||||||
|
# Example
|
||||||
|
|
||||||
|
For Example, See https://github.com/mkalioby/AutoDeploy/commit/5f1d94b1804e0aa33c79e9e8530ce849d9eb78cc in AutDeploy Project
|
||||||
|
|
||||||
|
# Table of Contents
|
||||||
|
* [Installation](installation.md)
|
||||||
|
* [Change Login Code](change_login.md)
|
||||||
|
|
||||||
58
docs/installation.md
Normal file
58
docs/installation.md
Normal file
@@ -0,0 +1,58 @@
|
|||||||
|
# Installation & Configuration
|
||||||
|
1. Install the package
|
||||||
|
```sh
|
||||||
|
pip install django-mfa2
|
||||||
|
```
|
||||||
|
1. in your settings.py add the application to your installed apps
|
||||||
|
```python
|
||||||
|
INSTALLED_APPS=(
|
||||||
|
'......',
|
||||||
|
'mfa',
|
||||||
|
'......')
|
||||||
|
```
|
||||||
|
1. Add the following settings to your file
|
||||||
|
```python
|
||||||
|
MFA_UNALLOWED_METHODS=() # Methods that shouldn't be allowed for the user
|
||||||
|
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_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
|
||||||
|
|
||||||
|
TOKEN_ISSUER_NAME="PROJECT_NAME" #TOTP Issuer name
|
||||||
|
|
||||||
|
U2F_APPID="https://localhost" #URL For U2
|
||||||
|
FIDO_SERVER_ID=u"localehost" # Server rp id for FIDO2, it the full domain of your project
|
||||||
|
FIDO_SERVER_NAME=u"PROJECT_NAME"
|
||||||
|
FIDO_LOGIN_URL=BASE_URL
|
||||||
|
```
|
||||||
|
|
||||||
|
**Method Names**
|
||||||
|
* U2F
|
||||||
|
* FIDO2
|
||||||
|
* TOTP
|
||||||
|
* Trusted_Devices
|
||||||
|
* Email
|
||||||
|
|
||||||
|
**Note**: Starting version 1.1, ~~FIDO_LOGIN_URL~~ isn't required for FIDO2 anymore.
|
||||||
|
|
||||||
|
1. Add mfa to urls.py
|
||||||
|
|
||||||
|
```python
|
||||||
|
import mfa
|
||||||
|
import mfa.TrustedDevice
|
||||||
|
urls_patterns= [
|
||||||
|
'...',
|
||||||
|
url(r'^mfa/', include('mfa.urls')),
|
||||||
|
url(r'devices/add$', mfa.TrustedDevice.add,name="mfa_add_new_trusted_device"), # This short link to add new trusted device
|
||||||
|
'....',
|
||||||
|
]
|
||||||
|
```
|
||||||
|
1. Provide `mfa_auth_base.html` in your templaes with block called 'head' and 'content'
|
||||||
|
The template will be included during the user login.
|
||||||
|
If you will use Email Token method, then you have to provide template named `mfa_email_token_template.html` that will content the format of the email with parameter named `user` and `otp`.
|
||||||
|
1. To match the look and feel of your project, MFA includes `base.html` but it needs blocks named `head` & `content` to added its content to it.
|
||||||
|
1. Somewhere in your app, add a link to 'mfa_home'
|
||||||
|
```<li><a href="{% url 'mfa_home' %}">Security</a> </li>```
|
||||||
|
|
||||||
|
Next, you need to [change your login code](change_login.md)
|
||||||
4
mfa/CHANGELOG.md
Normal file
4
mfa/CHANGELOG.md
Normal file
@@ -0,0 +1,4 @@
|
|||||||
|
# Change Log
|
||||||
|
|
||||||
|
## v1.2.0
|
||||||
|
* Added: MFA_HIDE_DISABLE setting option to disable users from deactivating their keys.
|
||||||
8
mfa/Common.py
Normal file
8
mfa/Common.py
Normal file
@@ -0,0 +1,8 @@
|
|||||||
|
from django.conf import settings
|
||||||
|
from django.core.mail import EmailMessage
|
||||||
|
|
||||||
|
def send(to,subject,body):
|
||||||
|
From = "%s <%s>" % (settings.EMAIL_FROM, settings.EMAIL_HOST_USER)
|
||||||
|
email = EmailMessage(subject,body,From,to)
|
||||||
|
email.content_subtype = "html"
|
||||||
|
return email.send(False)
|
||||||
16
mfa/Email.py
16
mfa/Email.py
@@ -5,19 +5,15 @@ from random import randint
|
|||||||
from .models import *
|
from .models import *
|
||||||
from django.template.context import RequestContext
|
from django.template.context import RequestContext
|
||||||
from .views import login
|
from .views import login
|
||||||
|
from .Common import send
|
||||||
def sendEmail(request,username,secret):
|
def sendEmail(request,username,secret):
|
||||||
from django.contrib.auth import get_user_model
|
from django.contrib.auth import get_user_model
|
||||||
User = get_user_model()
|
User = get_user_model()
|
||||||
user=User.objects.get(username=username)
|
key = getattr(User, 'USERNAME_FIELD', 'username')
|
||||||
print secret
|
kwargs = {key: username}
|
||||||
|
user = User.objects.get(**kwargs)
|
||||||
res=render_to_response("mfa_email_token_template.html",{"request":request,"user":user,'otp':secret})
|
res=render_to_response("mfa_email_token_template.html",{"request":request,"user":user,'otp':secret})
|
||||||
from django.conf import settings
|
return send([user.email],"OTP", res.content)
|
||||||
from django.core.mail import EmailMessage
|
|
||||||
From = "%s <%s>" % (settings.EMAIL_FROM, settings.EMAIL_HOST_USER)
|
|
||||||
email = EmailMessage("OTP",res.content,From,[user.email] )
|
|
||||||
email.content_subtype = "html"
|
|
||||||
return email.send(False)
|
|
||||||
|
|
||||||
def start(request):
|
def start(request):
|
||||||
context = csrf(request)
|
context = csrf(request)
|
||||||
@@ -34,7 +30,7 @@ def start(request):
|
|||||||
context["invalid"] = True
|
context["invalid"] = True
|
||||||
else:
|
else:
|
||||||
request.session["email_secret"] = str(randint(0,100000))
|
request.session["email_secret"] = str(randint(0,100000))
|
||||||
if sendEmail(request, request.session["base_username"], request.session["email_secret"]):
|
if sendEmail(request, request.user.username, request.session["email_secret"]):
|
||||||
context["sent"] = True
|
context["sent"] = True
|
||||||
return render_to_response("Email/Add.html", context, context_instance=RequestContext(request))
|
return render_to_response("Email/Add.html", context, context_instance=RequestContext(request))
|
||||||
def auth(request):
|
def auth(request):
|
||||||
|
|||||||
14
mfa/FIDO2.py
14
mfa/FIDO2.py
@@ -12,7 +12,7 @@ from django.conf import settings
|
|||||||
from .models import *
|
from .models import *
|
||||||
from fido2.utils import websafe_decode,websafe_encode
|
from fido2.utils import websafe_decode,websafe_encode
|
||||||
from fido2.ctap2 import AttestedCredentialData
|
from fido2.ctap2 import AttestedCredentialData
|
||||||
from views import login
|
from .views import login
|
||||||
import datetime
|
import datetime
|
||||||
from django.utils import timezone
|
from django.utils import timezone
|
||||||
|
|
||||||
@@ -34,11 +34,11 @@ def begin_registeration(request):
|
|||||||
}, getUserCredentials(request.user.username))
|
}, getUserCredentials(request.user.username))
|
||||||
request.session['fido_state'] = state
|
request.session['fido_state'] = state
|
||||||
|
|
||||||
return HttpResponse(cbor.dumps(registration_data),content_type='application/octet-stream')
|
return HttpResponse(cbor.encode(registration_data),content_type='application/octet-stream')
|
||||||
@csrf_exempt
|
@csrf_exempt
|
||||||
def complete_reg(request):
|
def complete_reg(request):
|
||||||
try:
|
try:
|
||||||
data = cbor.loads(request.body)[0]
|
data = cbor.decode(request.body)
|
||||||
|
|
||||||
client_data = ClientData(data['clientDataJSON'])
|
client_data = ClientData(data['clientDataJSON'])
|
||||||
att_obj = AttestationObject((data['attestationObject']))
|
att_obj = AttestationObject((data['attestationObject']))
|
||||||
@@ -79,7 +79,7 @@ def authenticate_begin(request):
|
|||||||
credentials=getUserCredentials(request.session.get("base_username",request.user.username))
|
credentials=getUserCredentials(request.session.get("base_username",request.user.username))
|
||||||
auth_data, state = server.authenticate_begin(credentials)
|
auth_data, state = server.authenticate_begin(credentials)
|
||||||
request.session['fido_state'] = state
|
request.session['fido_state'] = state
|
||||||
return HttpResponse(cbor.dumps(auth_data),content_type="application/octet-stream")
|
return HttpResponse(cbor.encode(auth_data),content_type="application/octet-stream")
|
||||||
|
|
||||||
@csrf_exempt
|
@csrf_exempt
|
||||||
def authenticate_complete(request):
|
def authenticate_complete(request):
|
||||||
@@ -87,7 +87,7 @@ def authenticate_complete(request):
|
|||||||
username=request.session.get("base_username",request.user.username)
|
username=request.session.get("base_username",request.user.username)
|
||||||
server=getServer()
|
server=getServer()
|
||||||
credentials=getUserCredentials(username)
|
credentials=getUserCredentials(username)
|
||||||
data = cbor.loads(request.body)[0]
|
data = cbor.decode(request.body)
|
||||||
credential_id = data['credentialId']
|
credential_id = data['credentialId']
|
||||||
client_data = ClientData(data['clientDataJSON'])
|
client_data = ClientData(data['clientDataJSON'])
|
||||||
auth_data = AuthenticatorData(data['authenticatorData'])
|
auth_data = AuthenticatorData(data['authenticatorData'])
|
||||||
@@ -112,6 +112,6 @@ def authenticate_complete(request):
|
|||||||
mfa["next_check"] = int((datetime.datetime.now()+ datetime.timedelta(
|
mfa["next_check"] = int((datetime.datetime.now()+ datetime.timedelta(
|
||||||
seconds=random.randint(settings.MFA_RECHECK_MIN, settings.MFA_RECHECK_MAX))).strftime("%s"))
|
seconds=random.randint(settings.MFA_RECHECK_MIN, settings.MFA_RECHECK_MAX))).strftime("%s"))
|
||||||
request.session["mfa"] = mfa
|
request.session["mfa"] = mfa
|
||||||
login(request)
|
res=login(request)
|
||||||
return HttpResponse(simplejson.dumps({'status':"OK","redirect":settings.FIDO_LOGIN_URL}),content_type="application/json")
|
return HttpResponse(simplejson.dumps({'status':"OK","redirect":res["location"]}),content_type="application/json")
|
||||||
return HttpResponse(simplejson.dumps({'status': "err"}),content_type="application/json")
|
return HttpResponse(simplejson.dumps({'status': "err"}),content_type="application/json")
|
||||||
|
|||||||
@@ -105,8 +105,13 @@ def start(request):
|
|||||||
|
|
||||||
def send_email(request):
|
def send_email(request):
|
||||||
body=render(request,"TrustedDevices/email.html",{}).content
|
body=render(request,"TrustedDevices/email.html",{}).content
|
||||||
from Registry_app.Common import send
|
from .Common import send
|
||||||
if send(request.user.email,"Add Trusted Device Link",body,delay=False):
|
e=request.user.email
|
||||||
|
if e=="":
|
||||||
|
e=request.session.get("user",{}).get("email","")
|
||||||
|
if e=="":
|
||||||
|
res = "User has no email on the system."
|
||||||
|
elif send([e],"Add Trusted Device Link",body):
|
||||||
res="Sent Successfully"
|
res="Sent Successfully"
|
||||||
else:
|
else:
|
||||||
res="Error occured, please try again later."
|
res="Error occured, please try again later."
|
||||||
|
|||||||
@@ -10,7 +10,7 @@ from django.template.context import RequestContext
|
|||||||
from django.template.context_processors import csrf
|
from django.template.context_processors import csrf
|
||||||
from django.conf import settings
|
from django.conf import settings
|
||||||
from django.http import HttpResponse
|
from django.http import HttpResponse
|
||||||
from.models import *
|
from .models import *
|
||||||
from .views import login
|
from .views import login
|
||||||
from django.utils import timezone
|
from django.utils import timezone
|
||||||
|
|
||||||
@@ -41,14 +41,14 @@ def validate(request,username):
|
|||||||
import datetime, random
|
import datetime, random
|
||||||
|
|
||||||
data = simplejson.loads(request.POST["response"])
|
data = simplejson.loads(request.POST["response"])
|
||||||
print "Checking Errors"
|
|
||||||
res= check_errors(request,data)
|
res= check_errors(request,data)
|
||||||
if res!=True:
|
if res!=True:
|
||||||
return res
|
return res
|
||||||
print "Checking Challenge"
|
|
||||||
challenge = request.session.pop('_u2f_challenge_')
|
challenge = request.session.pop('_u2f_challenge_')
|
||||||
device, c, t = complete_authentication(challenge, data, [settings.U2F_APPID])
|
device, c, t = complete_authentication(challenge, data, [settings.U2F_APPID])
|
||||||
print device
|
|
||||||
key=User_Keys.objects.get(username=username,properties__shas="$.device.publicKey=%s"%device["publicKey"])
|
key=User_Keys.objects.get(username=username,properties__shas="$.device.publicKey=%s"%device["publicKey"])
|
||||||
key.last_used=timezone.now()
|
key.last_used=timezone.now()
|
||||||
key.save()
|
key.save()
|
||||||
|
|||||||
@@ -1 +1,10 @@
|
|||||||
import urls
|
# @property
|
||||||
|
# def urls():
|
||||||
|
# import django
|
||||||
|
# if django.VERSION < (1, 9):
|
||||||
|
# from .mfa_urls import url_patterns
|
||||||
|
# return url_patterns, 'mfa', ''
|
||||||
|
# else:
|
||||||
|
# from .mfa_urls import url_patterns
|
||||||
|
# return url_patterns,'mfa'
|
||||||
|
#
|
||||||
|
|||||||
4
mfa/apps.py
Normal file
4
mfa/apps.py
Normal file
@@ -0,0 +1,4 @@
|
|||||||
|
from django.apps import AppConfig
|
||||||
|
class myAppNameConfig(AppConfig):
|
||||||
|
name = 'mfa'
|
||||||
|
verbose_name = 'A Much Better Name'
|
||||||
@@ -1,8 +1,6 @@
|
|||||||
import pyotp
|
import pyotp
|
||||||
from .models import *
|
from .models import *
|
||||||
import TrustedDevice
|
from . import TrustedDevice, U2F, FIDO2, totp
|
||||||
import U2F, FIDO2
|
|
||||||
import totp
|
|
||||||
import simplejson
|
import simplejson
|
||||||
from django.shortcuts import HttpResponse
|
from django.shortcuts import HttpResponse
|
||||||
from mfa.views import verify,goto
|
from mfa.views import verify,goto
|
||||||
|
|||||||
@@ -5,8 +5,13 @@ from django.db import models, migrations
|
|||||||
import jsonfield.fields
|
import jsonfield.fields
|
||||||
|
|
||||||
|
|
||||||
class Migration(migrations.Migration):
|
def modify_json(apps, schema_editor):
|
||||||
|
from django.conf import settings
|
||||||
|
if "mysql" in settings.DATABASES.get("default", {}).get("engine", ""):
|
||||||
|
migrations.RunSQL("alter table mfa_user_keys modify column properties json;")
|
||||||
|
|
||||||
|
|
||||||
|
class Migration(migrations.Migration):
|
||||||
dependencies = [
|
dependencies = [
|
||||||
('mfa', '0004_user_keys_enabled'),
|
('mfa', '0004_user_keys_enabled'),
|
||||||
]
|
]
|
||||||
@@ -21,5 +26,5 @@ class Migration(migrations.Migration):
|
|||||||
name='properties',
|
name='properties',
|
||||||
field=jsonfield.fields.JSONField(null=True),
|
field=jsonfield.fields.JSONField(null=True),
|
||||||
),
|
),
|
||||||
migrations.RunSQL("alter table mfa_user_keys modify column properties json;")
|
migrations.RunPython(modify_json)
|
||||||
]
|
]
|
||||||
|
|||||||
@@ -2,8 +2,7 @@ from django.db import models
|
|||||||
from jsonfield import JSONField
|
from jsonfield import JSONField
|
||||||
from jose import jwt
|
from jose import jwt
|
||||||
from django.conf import settings
|
from django.conf import settings
|
||||||
from jsonLookup import hasLookup,shasLookup
|
from jsonLookup import shasLookup
|
||||||
JSONField.register_lookup(hasLookup)
|
|
||||||
JSONField.register_lookup(shasLookup)
|
JSONField.register_lookup(shasLookup)
|
||||||
|
|
||||||
class User_Keys(models.Model):
|
class User_Keys(models.Model):
|
||||||
@@ -18,4 +17,9 @@ class User_Keys(models.Model):
|
|||||||
if self.key_type == "Trusted Device" and self.properties.get("signature","") == "":
|
if self.key_type == "Trusted Device" and self.properties.get("signature","") == "":
|
||||||
self.properties["signature"]= jwt.encode({"username": self.username, "key": self.properties["key"]}, settings.SECRET_KEY)
|
self.properties["signature"]= jwt.encode({"username": self.username, "key": self.properties["key"]}, settings.SECRET_KEY)
|
||||||
super(User_Keys, self).save(force_insert=force_insert, force_update=force_update, using=using, update_fields=update_fields)
|
super(User_Keys, self).save(force_insert=force_insert, force_update=force_update, using=using, update_fields=update_fields)
|
||||||
|
def __unicode__(self):
|
||||||
|
return "%s -- %s"%(self.username,self.key_type)
|
||||||
|
def __str__(self):
|
||||||
|
return self.__unicode__()
|
||||||
|
class Meta:
|
||||||
|
app_label='mfa'
|
||||||
@@ -20,6 +20,7 @@
|
|||||||
$("#modal-footer").prepend("<button id='actionBtn' class='btn btn-danger' onclick='confirmDel("+id+")'>Confirm Deletion</button>")
|
$("#modal-footer").prepend("<button id='actionBtn' class='btn btn-danger' onclick='confirmDel("+id+")'>Confirm Deletion</button>")
|
||||||
$("#popUpModal").modal()
|
$("#popUpModal").modal()
|
||||||
}
|
}
|
||||||
|
{% if not HIDE_DISABLE %}
|
||||||
function toggleKey(id) {
|
function toggleKey(id) {
|
||||||
$.ajax({
|
$.ajax({
|
||||||
url:"{% url 'toggle_key' %}?id="+id,
|
url:"{% url 'toggle_key' %}?id="+id,
|
||||||
@@ -33,6 +34,7 @@
|
|||||||
}
|
}
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
{% endif %}
|
||||||
</script>
|
</script>
|
||||||
<link href="{% static 'mfa/css/bootstrap-toggle.min.css' %}" rel="stylesheet">
|
<link href="{% static 'mfa/css/bootstrap-toggle.min.css' %}" rel="stylesheet">
|
||||||
<script src="{% static 'mfa/js/bootstrap-toggle.min.js'%}"></script>
|
<script src="{% static 'mfa/js/bootstrap-toggle.min.js'%}"></script>
|
||||||
@@ -87,8 +89,16 @@
|
|||||||
<td>{{ key.expires }}</td>
|
<td>{{ key.expires }}</td>
|
||||||
<td>{% if key.device %}{{ key.device }}{% endif %}</td>
|
<td>{% if key.device %}{{ key.device }}{% endif %}</td>
|
||||||
<td>{{ key.last_used }}</td>
|
<td>{{ key.last_used }}</td>
|
||||||
<td><input type="checkbox" id="toggle_{{ key.id }}" {% if key.enabled %}checked{% endif %} data-onstyle="success" data-offstyle="danger" onchange="toggleKey({{ key.id }})" data-toggle="toggle"></td>
|
{% if key.key_type in HIDE_DISABLE %}
|
||||||
<td><a href="javascript:void(0)" onclick="deleteKey({{ key.id }},'{{ key.key_type }}')"> <span class="fa fa-trash"></span></a></td>
|
<td>{% if key.enabled %}On{% else %} Off{% endif %}</td>
|
||||||
|
{% else %}
|
||||||
|
<td><input type="checkbox" id="toggle_{{ key.id }}" {% if key.enabled %}checked{% endif %} data-onstyle="success" data-offstyle="danger" onchange="toggleKey({{ key.id }})" data-toggle="toggle" class="status_chk"></td>
|
||||||
|
{% endif %}
|
||||||
|
<td>{% if key.key_type in HIDE_DISABLE %}
|
||||||
|
----
|
||||||
|
{% else %}
|
||||||
|
<a href="javascript:void(0)" onclick="deleteKey({{ key.id }},'{{ key.key_type }}')"> <span class="fa fa-trash"></span></a></td>
|
||||||
|
{% endif %}
|
||||||
</tr>
|
</tr>
|
||||||
{% empty %}
|
{% empty %}
|
||||||
<tr><td colspan="7" align="center">You didn't have any keys yet.</td> </tr>
|
<tr><td colspan="7" align="center">You didn't have any keys yet.</td> </tr>
|
||||||
|
|||||||
@@ -62,7 +62,6 @@
|
|||||||
<fieldset>
|
<fieldset>
|
||||||
<div class="row">
|
<div class="row">
|
||||||
<div class="col-sm-12 col-md-12">
|
<div class="col-sm-12 col-md-12">
|
||||||
{# <img class="profile-img" src="{{ STATIC_URL }}img/users.png" alt="">#}
|
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<div class="row">
|
<div class="row">
|
||||||
|
|||||||
@@ -1,4 +1,5 @@
|
|||||||
{% extends "base.html" %}
|
{% extends "base.html" %}
|
||||||
|
{% load static %}
|
||||||
{% block head %}
|
{% block head %}
|
||||||
<style>
|
<style>
|
||||||
#two-factor-steps {
|
#two-factor-steps {
|
||||||
@@ -10,7 +11,7 @@
|
|||||||
margin: 0px;
|
margin: 0px;
|
||||||
}
|
}
|
||||||
</style>
|
</style>
|
||||||
<script src="{{ STATIC_URL }}js/u2f-api.js" type="text/javascript"></script>
|
<script src="{% static 'mfa/js/u2f-api.js' %}" type="text/javascript"></script>
|
||||||
<script type="text/javascript">
|
<script type="text/javascript">
|
||||||
$(document).ready(function addToken() {
|
$(document).ready(function addToken() {
|
||||||
data=JSON.parse('{{ token|safe }}')
|
data=JSON.parse('{{ token|safe }}')
|
||||||
|
|||||||
@@ -1,3 +1,4 @@
|
|||||||
|
{% load static %}
|
||||||
<div class="row">
|
<div class="row">
|
||||||
|
|
||||||
<div class="col-sm-10 col-sm-offset-1 col-xs-12 col-md-10 col-md-offset-1 col-lg-8 col-lg-offset-2">
|
<div class="col-sm-10 col-sm-offset-1 col-xs-12 col-md-10 col-md-offset-1 col-lg-8 col-lg-offset-2">
|
||||||
@@ -34,7 +35,7 @@
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<script src="{{ STATIC_URL }}js/u2f-api.js" type="text/javascript"></script>
|
<script src="{% static 'mfa/js/u2f-api.js' %}" type="text/javascript"></script>
|
||||||
|
|
||||||
<script type="text/javascript">
|
<script type="text/javascript">
|
||||||
$(document).ready(function () {
|
$(document).ready(function () {
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
from django.conf.urls import url
|
from django.conf.urls import url
|
||||||
from . import views,totp,U2F,TrustedDevice,helpers,FIDO2,Email
|
|
||||||
|
|
||||||
|
from . import views,totp,U2F,TrustedDevice,helpers,FIDO2,Email
|
||||||
|
app_name='mfa'
|
||||||
urlpatterns = [
|
urlpatterns = [
|
||||||
url(r'totp/start/', totp.start , name="start_new_otop"),
|
url(r'totp/start/', totp.start , name="start_new_otop"),
|
||||||
url(r'totp/getToken', totp.getToken , name="get_new_otop"),
|
url(r'totp/getToken', totp.getToken , name="get_new_otop"),
|
||||||
|
|||||||
14
mfa/views.py
14
mfa/views.py
@@ -1,22 +1,26 @@
|
|||||||
from django.shortcuts import render,render_to_response
|
from django.shortcuts import render,render_to_response
|
||||||
from django.http import HttpResponse,HttpResponseRedirect
|
from django.http import HttpResponse,HttpResponseRedirect
|
||||||
from .models import *
|
from .models import *
|
||||||
from django.core.urlresolvers import reverse
|
try:
|
||||||
|
from django.urls import reverse
|
||||||
|
except:
|
||||||
|
from django.core.urlresolvers import reverse
|
||||||
from django.template.context_processors import csrf
|
from django.template.context_processors import csrf
|
||||||
from django.template.context import RequestContext
|
from django.template.context import RequestContext
|
||||||
from django.conf import settings
|
from django.conf import settings
|
||||||
import TrustedDevice
|
from . import TrustedDevice
|
||||||
from user_agents import parse
|
from user_agents import parse
|
||||||
def index(request):
|
def index(request):
|
||||||
keys=[]
|
keys=[]
|
||||||
context={"keys":User_Keys.objects.filter(username=request.user.username),"UNALLOWED_AUTHEN_METHODS":settings.MFA_UNALLOWED_METHODS}
|
context={"keys":User_Keys.objects.filter(username=request.user.username),"UNALLOWED_AUTHEN_METHODS":settings.MFA_UNALLOWED_METHODS
|
||||||
|
,"HIDE_DISABLE":getattr(settings,"MFA_HIDE_DISABLE",[])}
|
||||||
for k in context["keys"]:
|
for k in context["keys"]:
|
||||||
if k.key_type =="Trusted Device" :
|
if k.key_type =="Trusted Device" :
|
||||||
setattr(k,"device",parse(k.properties.get("user_agent","-----")))
|
setattr(k,"device",parse(k.properties.get("user_agent","-----")))
|
||||||
elif k.key_type == "FIDO2":
|
elif k.key_type == "FIDO2":
|
||||||
setattr(k,"device",k.properties.get("type","----"))
|
setattr(k,"device",k.properties.get("type","----"))
|
||||||
keys.append(k)
|
keys.append(k)
|
||||||
context["keys"]=keys
|
context["keys"]=keys
|
||||||
return render_to_response("MFA.html",context,context_instance=RequestContext(request))
|
return render_to_response("MFA.html",context,context_instance=RequestContext(request))
|
||||||
|
|
||||||
def verify(request,username):
|
def verify(request,username):
|
||||||
@@ -24,7 +28,7 @@ def verify(request,username):
|
|||||||
#request.session["base_password"] = password
|
#request.session["base_password"] = password
|
||||||
keys=User_Keys.objects.filter(username=username,enabled=1)
|
keys=User_Keys.objects.filter(username=username,enabled=1)
|
||||||
methods=list(set([k.key_type for k in keys]))
|
methods=list(set([k.key_type for k in keys]))
|
||||||
print methods
|
|
||||||
if "Trusted Device" in methods and not request.session.get("checked_trusted_device",False):
|
if "Trusted Device" in methods and not request.session.get("checked_trusted_device",False):
|
||||||
if TrustedDevice.verify(request):
|
if TrustedDevice.verify(request):
|
||||||
return login(request)
|
return login(request)
|
||||||
|
|||||||
8
mkdocs.yml
Normal file
8
mkdocs.yml
Normal file
@@ -0,0 +1,8 @@
|
|||||||
|
site_name: MkLorum
|
||||||
|
nav:
|
||||||
|
- Home: index.md
|
||||||
|
- Installation: installation.md
|
||||||
|
- Code Changes: change_login.md
|
||||||
|
theme: readthedocs
|
||||||
|
markdown_extensions:
|
||||||
|
- fenced_code
|
||||||
33
setup.py
33
setup.py
@@ -4,17 +4,19 @@ from setuptools import find_packages, setup
|
|||||||
|
|
||||||
setup(
|
setup(
|
||||||
name='django-mfa2',
|
name='django-mfa2',
|
||||||
version='0.9.0',
|
version='1.3.0',
|
||||||
description='Allows user to add 2FA to their accounts',
|
description='Allows user to add 2FA to their accounts',
|
||||||
|
long_description=open("README.md").read(),
|
||||||
|
long_description_content_type="text/markdown",
|
||||||
|
|
||||||
author='Mohamed El-Kalioby',
|
author='Mohamed El-Kalioby',
|
||||||
author_email = 'mkalioby@mkalioby.com',
|
author_email = 'mkalioby@mkalioby.com',
|
||||||
url = 'https://github.com/mkalioby/django-mfa2/',
|
url = 'https://github.com/mkalioby/django-mfa2/',
|
||||||
|
|
||||||
download_url='https://github.com/mkalioby/django-mfa2/',
|
download_url='https://github.com/mkalioby/django-mfa2/',
|
||||||
license='MIT',
|
license='MIT',
|
||||||
packages=find_packages(),
|
packages=find_packages(),
|
||||||
install_requires=[
|
install_requires=[
|
||||||
'Django>=1.7',
|
'django >= 1.7',
|
||||||
'jsonfield',
|
'jsonfield',
|
||||||
'simplejson',
|
'simplejson',
|
||||||
'pyotp',
|
'pyotp',
|
||||||
@@ -22,9 +24,32 @@ setup(
|
|||||||
'ua-parser',
|
'ua-parser',
|
||||||
'user-agents',
|
'user-agents',
|
||||||
'python-jose',
|
'python-jose',
|
||||||
'fido2==0.5'
|
'fido2 == 0.6',
|
||||||
'jsonLookup'
|
'jsonLookup'
|
||||||
],
|
],
|
||||||
|
python_requires=">=2.7, !=3.0.*, !=3.1.*, !=3.2.*, !=3.3.*",
|
||||||
include_package_data=True,
|
include_package_data=True,
|
||||||
zip_safe=False, # because we're including static files
|
zip_safe=False, # because we're including static files
|
||||||
|
classifiers=[
|
||||||
|
"Development Status :: 5 - Production/Stable",
|
||||||
|
"Environment :: Web Environment",
|
||||||
|
"Framework :: Django",
|
||||||
|
"Framework :: Django :: 1.7",
|
||||||
|
"Framework :: Django :: 1.8",
|
||||||
|
"Framework :: Django :: 1.9",
|
||||||
|
"Framework :: Django :: 1.10",
|
||||||
|
"Framework :: Django :: 1.11",
|
||||||
|
"Framework :: Django :: 2.0",
|
||||||
|
"Framework :: Django :: 2.1",
|
||||||
|
"Intended Audience :: Developers",
|
||||||
|
"Operating System :: OS Independent",
|
||||||
|
"Programming Language :: Python",
|
||||||
|
"Programming Language :: Python :: 2",
|
||||||
|
"Programming Language :: Python :: 2.7",
|
||||||
|
"Programming Language :: Python :: 3",
|
||||||
|
"Programming Language :: Python :: 3.4",
|
||||||
|
"Programming Language :: Python :: 3.5",
|
||||||
|
"Programming Language :: Python :: 3.6",
|
||||||
|
"Topic :: Software Development :: Libraries :: Python Modules",
|
||||||
|
]
|
||||||
)
|
)
|
||||||
|
|||||||
Reference in New Issue
Block a user