mirror of
https://github.com/freedombox/FreedomBox.git
synced 2026-07-29 12:09:37 +00:00
users: Add support for logging in with passkeys
Tests:
- Login
- Login using passkeys works on testing container and stable container.
- Login page show 'Log in with passkey' button as expected along with key
icon.
- On GNOME's Web browser, the login page does not show an error on load.
Clicking on 'Log in with passkey' shows the error: 'Logging in with passkey
failed: Browser does not support passkeys.'
- On Chromium browser, with invalid TLS certficiate, the login page does not
show an error on load. Clicking on 'Log in with passkey' shows the error:
'Logging in with passkey failed: NotAllowedError: WebAuthn is not supported
on sites with TLS certificate errors.'
- Raising an error in the passkey_login_begin() method shows the error message
when login page is loaded. Raising an error in the passkey_login_complete
method shows the error message after passkey is unlocked. In both cases, 500
is HTTP status code.
- With primary hardware key register passkey each for 'tester' and 'tester2'
accounts.
- With secondary hardware key register passkey for 'tester' account.
- In login page, loading the page shows the console message 'Signing in with a
passkey. Condition: true'.
- In login page, when username field is clicked, 'passkey' is shown in the
autofill popup options. Selecting it prompts for hardware PIN and touch.
User is logged in.
- In login page, when 'Log in with passkey' is clicked, console message is
show 'Log in initiated with button, conditional mediation aborted.'.
Hardware PIN and touch is prompted. User is logged in.
- During autofill login, canceling the hardware key PIN shows no error alert.
Autofill passkey login is not available.
- During autofill login, canceling the hardware touch prompt shows no error
alert. Autofill passkey login is not available.
- During button login, canceling the hardware key PIN shows '...user denied
permission' error alert. Autofill passkey login is not available.
- During button login, canceling the hardware touch prompt shows no '...user
denied permission' error alert. Autofill passkey login is not available.
- When multiple attempts fail, multiple error alerts are shown.
- During login, with primary key account selection dialog is shown. Selecting
'tester' logs into 'tester' account. Selecting 'tester2' logs into 'tester2'
account.
- During login, with secondary key, account selection dialog is not shown.
User is logged into the 'tester' account.
- Password based login continues to work as usual on Firefox, Chromium, and
GNOME's web.
- Logout, then visit /freedombox/sys/. This redirects to login page. After
login with passkey the browser is redirected to /freedombox/sys page.
- After passkey login, 'Last Used' for that key is updated. The value is not
updated for remaining keys of the account.
- After successful login, database is updated with the latest signature
counter.
- After successful login, for a user account with Spanish set as language, the
UI language changes to Spanish.
- If a key has been removed from list of passkeys and that passkey is
attempted for login, 'Passkey used is not known' error alert is shown.
Signed-off-by: Sunil Mohan Adapa <sunil@medhas.org>
Reviewed-by: James Valleroy <jvalleroy@mailbox.org>
This commit is contained in:
parent
1a8868f0cd
commit
9d6c74c887
@ -36,7 +36,7 @@ class AuthenticationForm(DjangoAuthenticationForm):
|
||||
self.fields['username'].widget.attrs.update({
|
||||
'autofocus': 'autofocus',
|
||||
'autocapitalize': 'none',
|
||||
'autocomplete': 'username'
|
||||
'autocomplete': 'username webauthn'
|
||||
})
|
||||
|
||||
|
||||
|
||||
@ -205,3 +205,120 @@ document.addEventListener('DOMContentLoaded', () => {
|
||||
'#passkey-delete-confirm-dialog .confirm');
|
||||
confirmDeleteButton.addEventListener('click', onPasskeyDeleteConfirmed);
|
||||
});
|
||||
|
||||
|
||||
let passkeyLoginAbortController = null;
|
||||
|
||||
/*
|
||||
* Login with a passkey. First send a request to the server to begin logging in
|
||||
* with passkey and get challenge and login operation options. Then request the
|
||||
* browser to talk to the authenticator to sign the challenge with a passkey.
|
||||
* Finally, pass the challenge signed with a known passkey along with other
|
||||
* results to the server.
|
||||
*/
|
||||
async function loginWithPasskey(conditionalMediation, csrfToken, next) {
|
||||
console.log('Signing in with a passkey. Conditional mediation: ',
|
||||
conditionalMediation);
|
||||
|
||||
if (!window.PublicKeyCredential) {
|
||||
if (!conditionalMediation) {
|
||||
const message = document.getElementById(
|
||||
'browser-does-not-support-passkeys').innerText.trim();
|
||||
handleError('Browser does not support passkeys', message);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
//
|
||||
// Request challenge and options from server.
|
||||
//
|
||||
const options = await jsonFetch('passkey-begin/', {
|
||||
'method': 'POST',
|
||||
body: new URLSearchParams({'csrfmiddlewaretoken': csrfToken})
|
||||
}, 'initiate passkey login');
|
||||
if (!options) {
|
||||
return;
|
||||
}
|
||||
|
||||
options['publicKey']['challenge'] = base64WebDecode(
|
||||
options['publicKey']['challenge']);
|
||||
|
||||
// Abort a previous login operation (such as conditional mediation operation
|
||||
// if it is running). Firefox automatically does this but Chrome does not.
|
||||
if (passkeyLoginAbortController) {
|
||||
console.log('Explicitly aborting previous passkey login operation.');
|
||||
passkeyLoginAbortController.abort();
|
||||
}
|
||||
|
||||
passkeyLoginAbortController = new AbortController();
|
||||
|
||||
//
|
||||
// Sign the server challenge with passkey stored in authenticator (via the
|
||||
// browser).
|
||||
//
|
||||
let credential;
|
||||
try {
|
||||
const getOptions = {
|
||||
'publicKey': options['publicKey'],
|
||||
'signal': passkeyLoginAbortController.signal
|
||||
};
|
||||
if (conditionalMediation) {
|
||||
getOptions['mediation'] = 'conditional';
|
||||
}
|
||||
credential = await navigator.credentials.get(getOptions);
|
||||
} catch (error) {
|
||||
if (conditionalMediation && error.name == 'AbortError') {
|
||||
// When user clicks on 'Log in with passkey', the process initiated
|
||||
// with conditional mediation will be aborted.
|
||||
console.log('Log in initiated with button, ' +
|
||||
'conditional mediation aborted.');
|
||||
return;
|
||||
}
|
||||
if (!conditionalMediation) {
|
||||
// Don't show error message or retry.
|
||||
handleError('Login with passkey failed.', error);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
// Send the signature and the authenticator response to the server to
|
||||
// complete the login process.
|
||||
let completeResponse = await jsonFetch('passkey-complete/', {
|
||||
'method': 'POST',
|
||||
'headers': {
|
||||
'Content-Type': 'application/json',
|
||||
'X-CSRFToken': csrfToken
|
||||
},
|
||||
'body': JSON.stringify(credential),
|
||||
}, 'login with passkey');
|
||||
if (!completeResponse) {
|
||||
return;
|
||||
}
|
||||
|
||||
console.log('Login with passkey succeeded.');
|
||||
window.location.href = next;
|
||||
}
|
||||
|
||||
/*
|
||||
* Attach an click event listener to 'Log in with passkey' button.
|
||||
*/
|
||||
document.addEventListener('DOMContentLoaded', async () => {
|
||||
const loginWithPasskeyButton = document.getElementById('login-with-passkey');
|
||||
if (!loginWithPasskeyButton) {
|
||||
// Not part of login page.
|
||||
return;
|
||||
}
|
||||
|
||||
const csrfToken = document.getElementsByName('csrfmiddlewaretoken')[0].value;
|
||||
const next = document.getElementsByName('next')[0].value;
|
||||
loginWithPasskeyButton.addEventListener('click', async (event) => {
|
||||
event.preventDefault();
|
||||
await loginWithPasskey(false, csrfToken, next);
|
||||
});
|
||||
|
||||
// Login with conditional mediation. This means that user will see a
|
||||
// 'passkey' option with autofill in the username field. The login method
|
||||
// will be wait in the navigator.credentials.get() call until user selects
|
||||
// that option. Don't await.
|
||||
loginWithPasskey(true, csrfToken, next);
|
||||
});
|
||||
|
||||
@ -5,12 +5,46 @@
|
||||
|
||||
{% load bootstrap %}
|
||||
{% load i18n %}
|
||||
{% load static %}
|
||||
{% load extras %}
|
||||
|
||||
{% block breadcrumbs %}
|
||||
{% endblock %}
|
||||
|
||||
{% block page_js %}
|
||||
<script type="text/javascript" src="{% static 'users/passkeys.js' %}" defer></script>
|
||||
{% endblock %}
|
||||
|
||||
{% block content %}
|
||||
|
||||
<div id="passkey-message-template" class="d-none">
|
||||
<div class="alert alert-danger alert-dismissible
|
||||
d-flex align-items-center fade show"
|
||||
role="alert">
|
||||
<div class="me-2">
|
||||
{% icon 'exclamation-triangle' %}
|
||||
<span class="visually-hidden">{% trans "Error:" %}</span>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
{% trans "Logging in with passkey failed: " %}
|
||||
<span class="message"></span>
|
||||
<button type="button" class="btn-close" data-bs-dismiss="alert"
|
||||
aria-label="{% trans "Close" %}">
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div id="localized-strings" class="d-none">
|
||||
<div id="browser-does-not-support-passkeys">
|
||||
{% trans "Browser does not support passkeys." %}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div id="passkey-messages">
|
||||
</div>
|
||||
|
||||
<form class="form form-login" method="post">
|
||||
|
||||
<div class="row">
|
||||
@ -28,4 +62,16 @@
|
||||
<input type="hidden" name="next" value="{{ next }}" />
|
||||
</form>
|
||||
|
||||
<div class="row text-center">
|
||||
<div class="col col-md-4 offset-md-4">
|
||||
<hr>
|
||||
|
||||
<a id="login-with-passkey" href="#" class="btn btn-default" role="button"
|
||||
title="{% trans 'Log in with passkey' %}">
|
||||
{% icon 'key' %}
|
||||
{% trans 'Log in with passkey' %}
|
||||
</a>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{% endblock %}
|
||||
|
||||
@ -29,6 +29,11 @@ urlpatterns = [
|
||||
r'^sys/users/(?P<username>[\w.@+-]+)/passkeys/'
|
||||
r'(?P<passkey_id>[\d]+)/edit/$',
|
||||
non_admin_view(views.PasskeyEdit.as_view()), name='passkey_edit'),
|
||||
re_path(r'^accounts/login/passkey-begin/$',
|
||||
public(views.passkey_login_begin), name='passkey_login_begin'),
|
||||
re_path(r'^accounts/login/passkey-complete/$',
|
||||
public(views.passkey_login_complete),
|
||||
name='passkey_login_complete'),
|
||||
re_path(
|
||||
r'^sys/users/(?P<username>[\w.@+-]+)/passkeys/'
|
||||
r'(?P<passkey_id>[\d]+)/delete/$',
|
||||
|
||||
@ -12,8 +12,10 @@ import axes.utils
|
||||
import django.views.generic
|
||||
import fido2.cbor
|
||||
import fido2.features
|
||||
import fido2.utils
|
||||
from django import shortcuts
|
||||
from django.contrib import messages
|
||||
from django.contrib.auth import login as auth_login
|
||||
from django.contrib.auth import logout as auth_logout
|
||||
from django.contrib.auth import update_session_auth_hash
|
||||
from django.contrib.auth.models import User
|
||||
@ -31,6 +33,7 @@ from django.views.generic.edit import (CreateView, DeleteView, FormView,
|
||||
UpdateView)
|
||||
from fido2 import webauthn
|
||||
from fido2.server import Fido2Server
|
||||
from fido2.webauthn import AttestedCredentialData, AuthenticationResponse
|
||||
|
||||
import plinth.modules.ssh.privileged as ssh_privileged
|
||||
from plinth import translation
|
||||
@ -446,3 +449,126 @@ class PasskeyDelete(DeleteView):
|
||||
def get_success_url(self):
|
||||
"""Return the URL to visit if form edit succeeds."""
|
||||
return reverse('users:passkeys', args=[self.kwargs['username']])
|
||||
|
||||
|
||||
@json_exception
|
||||
@require_POST
|
||||
def passkey_login_begin(request):
|
||||
"""Begin the process of logging-in with passwords."""
|
||||
# Domain
|
||||
domain = request.get_host().partition(':')[0]
|
||||
|
||||
# Begin Authentication
|
||||
server = get_fido2_server(domain)
|
||||
request_options, state = server.authenticate_begin(
|
||||
credentials=None,
|
||||
user_verification=fido2.webauthn.UserVerificationRequirement.REQUIRED,
|
||||
challenge=None)
|
||||
|
||||
logger.info('Passkey login begins')
|
||||
|
||||
request.session['fido2_server_state'] = state
|
||||
return JsonResponse(dict(request_options))
|
||||
|
||||
|
||||
@json_exception
|
||||
@require_POST
|
||||
def passkey_login_complete(request):
|
||||
"""Complete the process of logging-in with passwords."""
|
||||
|
||||
def _response(result: bool, error_string: str):
|
||||
"""Return a JsonResponse object."""
|
||||
status = 200
|
||||
if not result:
|
||||
status = 400
|
||||
logger.error('Error completing passkey login: %s', error_string)
|
||||
|
||||
return JsonResponse({
|
||||
'result': result,
|
||||
'error_string': error_string
|
||||
}, status=status)
|
||||
|
||||
try:
|
||||
response = json.loads(request.body)
|
||||
except json.decoder.JSONDecodeError as exception:
|
||||
return _response(False, str(exception))
|
||||
|
||||
# Domain
|
||||
domain = request.get_host().partition(':')[0]
|
||||
|
||||
# State
|
||||
state = request.session.get('fido2_server_state')
|
||||
|
||||
# Complete Authentication
|
||||
server = get_fido2_server(domain)
|
||||
try:
|
||||
authentication_repsonse = AuthenticationResponse.from_dict(response)
|
||||
|
||||
if hasattr(authentication_repsonse, 'raw_id'):
|
||||
# Library python3-fido2 >= 2.0.0
|
||||
credential_id = authentication_repsonse.raw_id
|
||||
else:
|
||||
# Library python3-fido2 < 2.0.0
|
||||
credential_id = authentication_repsonse.id
|
||||
|
||||
selected_passkeys = UserPasskey.objects.filter(
|
||||
credential_id=credential_id)
|
||||
|
||||
if not len(selected_passkeys):
|
||||
return _response(False, _('Passkey used is not known.'))
|
||||
|
||||
selected_passkey = selected_passkeys[0]
|
||||
|
||||
credentials = [
|
||||
AttestedCredentialData.create(
|
||||
aaguid=selected_passkey.aaguid.bytes,
|
||||
credential_id=selected_passkey.credential_id,
|
||||
public_key=fido2.cbor.decode(selected_passkey.public_key))
|
||||
]
|
||||
credential_data = server.authenticate_complete(
|
||||
state=state, credentials=credentials,
|
||||
response=authentication_repsonse)
|
||||
except Exception as exception:
|
||||
return _response(False, str(exception))
|
||||
|
||||
try:
|
||||
passkeys = UserPasskey.objects.filter(
|
||||
credential_id=credential_data.credential_id,
|
||||
public_key=fido2.cbor.encode(credential_data.public_key))
|
||||
except Exception as exception:
|
||||
return _response(False, str(exception))
|
||||
|
||||
if not len(passkeys):
|
||||
return _response(False, _('Passkey used is not known.'))
|
||||
|
||||
assert len(passkeys) == 1 # credential_id is a unique field.
|
||||
|
||||
passkey = passkeys[0]
|
||||
|
||||
# Detect cloned passkeys using signature counter.
|
||||
# See: https://www.w3.org/TR/webauthn/#signature-counter
|
||||
authenticator_data = authentication_repsonse.response.authenticator_data
|
||||
signature_counter = authenticator_data.counter
|
||||
if (passkey.signature_counter and signature_counter
|
||||
and signature_counter <= passkey.signature_counter):
|
||||
# TODO: Notify user of a cloned passkey
|
||||
logger.warning(
|
||||
'Potentially cloned passkey detected. Passkey ID in DB - %s, '
|
||||
'credential ID - %s, signature counters - %s <= %s', passkey.id,
|
||||
fido2.utils.websafe_encode(passkey.credential_id),
|
||||
signature_counter, passkey.signature_counter)
|
||||
|
||||
passkey.signature_counter = signature_counter
|
||||
passkey.save() # Update the last used time
|
||||
|
||||
# Needed by login(), stored in session, and used for permission checks.
|
||||
passkey.user.backend = 'django.contrib.auth.backends.ModelBackend'
|
||||
|
||||
# Perform user login into Django
|
||||
auth_login(request, passkey.user)
|
||||
response = _response(True, None)
|
||||
if request.user.is_authenticated:
|
||||
translation.set_language(request, response,
|
||||
request.user.userprofile.language)
|
||||
|
||||
return response
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user