mirror of
https://github.com/GSA/notifications-admin.git
synced 2026-08-05 14:11:41 -04:00
Support registering a new authenticator
This adds Yubico's FIDO2 library and two APIs for working with the "navigator.credentials.create()" function in JavaScript. The GET API uses the library to generate options for the "create()" function, and the POST API decodes and verifies the resulting credential. While the options and response are dict-like, CBOR is necessary to encode some of the byte-level values, which can't be represented in JSON. Much of the code here is based on the Yubico library example [1][2]. Implementation notes: - There are definitely better ways to alert the user about failure, but window.alert() will do for the time being. Using location.reload() is also a bit jarring if the page scrolls, but not a major issue. - Ideally we would use window.fetch() to do AJAX calls, but we don't have a polyfill for this, and we use $.ajax() elsewhere [3]. We need to do a few weird tricks [6] to stop jQuery trashing the data. - The FIDO2 server doesn't serve web requests; it's just a "server" in the sense of WebAuthn terminology. It lives in its own module, since it needs to be initialised with the app / config. - $.ajax returns a promise-like object. Although we've used ".fail()" elsewhere [3], I couldn't find a stub object that supports it, so I've gone for ".catch()", and used a Promise stub object in tests. - WebAuthn only works over HTTPS, but there's an exception for "localhost" [4]. However, the library is a bit too strict [5], so we have to disable origin verification to avoid needing HTTPS for dev work. [1]:c42d9628a4/examples/server/server.py[2]:c42d9628a4/examples/server/static/register.html[3]:91453d3639/app/assets/javascripts/updateContent.js (L33)[4]: https://stackoverflow.com/questions/55971593/navigator-credentials-is-null-on-local-server [5]:c42d9628a4/fido2/rpid.py (L69)[6]: https://stackoverflow.com/questions/12394622/does-jquery-ajax-or-load-allow-for-responsetype-arraybuffer
This commit is contained in:
@@ -31,7 +31,7 @@ from werkzeug.exceptions import HTTPException as WerkzeugHTTPException
|
||||
from werkzeug.exceptions import abort
|
||||
from werkzeug.local import LocalProxy
|
||||
|
||||
from app import proxy_fix
|
||||
from app import proxy_fix, webauthn_server
|
||||
from app.asset_fingerprinter import asset_fingerprinter
|
||||
from app.commands import setup_commands
|
||||
from app.config import configs
|
||||
@@ -208,6 +208,7 @@ def create_app(application):
|
||||
client.init_app(application)
|
||||
|
||||
logging.init_app(application)
|
||||
webauthn_server.init_app(application)
|
||||
|
||||
login_manager.login_view = 'main.sign_in'
|
||||
login_manager.login_message_category = 'default'
|
||||
|
||||
@@ -3,12 +3,67 @@
|
||||
|
||||
window.GOVUK.Modules.RegisterSecurityKey = function() {
|
||||
this.start = function(component) {
|
||||
|
||||
$(component)
|
||||
.on('click', function(event) {
|
||||
event.preventDefault();
|
||||
alert('not implemented');
|
||||
|
||||
fetchWebAuthnCreateOptions()
|
||||
.then((data) => {
|
||||
var options = window.CBOR.decode(data);
|
||||
// triggers browser dialogue to select authenticator
|
||||
return window.navigator.credentials.create(options);
|
||||
})
|
||||
.then((credential) => {
|
||||
return postWebAuthnCreateResponse(
|
||||
credential.response, component.data('csrfToken')
|
||||
);
|
||||
})
|
||||
.then(() => {
|
||||
window.location.reload();
|
||||
})
|
||||
.catch((error) => {
|
||||
// there may be other kinds of error we should catch here
|
||||
// https://github.com/w3c/webauthn/issues/876
|
||||
if (error instanceof DOMException) {
|
||||
console.error(error);
|
||||
// not all browsers show an error dialogue, so to be safe
|
||||
// we manually pop one open here (to be improved in future!)
|
||||
alert('Error communicating with device.\n\n' + error.message);
|
||||
} else {
|
||||
// for web requests we need to manually alert the user
|
||||
// $.ajax seems to log by itself, but that's not visible
|
||||
alert('Error during registration. Please try again.');
|
||||
}
|
||||
});
|
||||
});
|
||||
};
|
||||
};
|
||||
|
||||
function fetchWebAuthnCreateOptions() {
|
||||
var xhrOverride = new XMLHttpRequest();
|
||||
xhrOverride.responseType = 'arraybuffer';
|
||||
|
||||
return $.ajax({
|
||||
url: '/webauthn/register',
|
||||
xhr: () => xhrOverride,
|
||||
dataType: 'x-binary',
|
||||
converters: { '* x-binary': (value) => value }
|
||||
});
|
||||
}
|
||||
|
||||
function postWebAuthnCreateResponse(response, csrf_token) {
|
||||
return $.ajax({
|
||||
url: '/webauthn/register',
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'X-CSRFToken': csrf_token
|
||||
},
|
||||
processData: false,
|
||||
contentType: 'application/cbor',
|
||||
data: window.CBOR.encode({
|
||||
attestationObject: new Uint8Array(response.attestationObject),
|
||||
clientDataJSON: new Uint8Array(response.clientDataJSON),
|
||||
})
|
||||
});
|
||||
}
|
||||
})(window);
|
||||
|
||||
@@ -42,4 +42,5 @@ from app.main.views import ( # noqa isort:skip
|
||||
uploads,
|
||||
user_profile,
|
||||
verify,
|
||||
webauthn_credentials,
|
||||
)
|
||||
|
||||
43
app/main/views/webauthn_credentials.py
Normal file
43
app/main/views/webauthn_credentials.py
Normal file
@@ -0,0 +1,43 @@
|
||||
from fido2 import cbor
|
||||
from flask import current_app, request, session
|
||||
from flask_login import current_user
|
||||
|
||||
from app.main import main
|
||||
from app.models.webauthn_credential import WebAuthnCredential
|
||||
from app.notify_client.user_api_client import user_api_client
|
||||
from app.utils import user_is_platform_admin
|
||||
|
||||
|
||||
@main.route('/webauthn/register')
|
||||
@user_is_platform_admin
|
||||
def webauthn_begin_register():
|
||||
server = current_app.webauthn_server
|
||||
|
||||
registration_data, state = server.register_begin(
|
||||
{
|
||||
"id": bytes(current_user.id, 'utf-8'),
|
||||
"name": current_user.email_address,
|
||||
"displayName": current_user.name,
|
||||
},
|
||||
credentials=[], # TODO: get from user
|
||||
user_verification="discouraged", # don't ask for PIN
|
||||
authenticator_attachment="cross-platform",
|
||||
)
|
||||
|
||||
session["webauthn_registration_state"] = state
|
||||
return cbor.encode(registration_data)
|
||||
|
||||
|
||||
@main.route('/webauthn/register', methods=['POST'])
|
||||
@user_is_platform_admin
|
||||
def webauthn_complete_register():
|
||||
credential = WebAuthnCredential.from_registration(
|
||||
session.pop("webauthn_registration_state"),
|
||||
cbor.decode(request.get_data()),
|
||||
)
|
||||
|
||||
user_api_client.create_webauthn_credential_for_user(
|
||||
current_user.id, credential
|
||||
)
|
||||
|
||||
return ''
|
||||
@@ -1,3 +1,10 @@
|
||||
import base64
|
||||
|
||||
from fido2 import cbor
|
||||
from fido2.client import ClientData
|
||||
from fido2.ctap2 import AttestationObject, AttestedCredentialData
|
||||
from flask import current_app
|
||||
|
||||
from app.models import JSONModel
|
||||
|
||||
|
||||
@@ -5,7 +12,40 @@ class WebAuthnCredential(JSONModel):
|
||||
ALLOWED_PROPERTIES = {
|
||||
'id',
|
||||
'name',
|
||||
'credential_data',
|
||||
'credential_data', # contains public key and credential ID for auth
|
||||
'registration_response', # sent to API for later auditing (not used)
|
||||
'created_at',
|
||||
'updated_at'
|
||||
}
|
||||
|
||||
@classmethod
|
||||
def from_registration(cls, state, response):
|
||||
server = current_app.webauthn_server
|
||||
|
||||
auth_data = server.register_complete(
|
||||
state,
|
||||
ClientData(response["clientDataJSON"]),
|
||||
AttestationObject(response["attestationObject"]),
|
||||
)
|
||||
|
||||
return cls({
|
||||
'name': 'Unnamed key',
|
||||
'credential_data': base64.b64encode(
|
||||
cbor.encode(auth_data.credential_data),
|
||||
),
|
||||
'registration_response': base64.b64encode(
|
||||
cbor.encode(response),
|
||||
)
|
||||
})
|
||||
|
||||
def to_credential_data(self):
|
||||
return AttestedCredentialData(
|
||||
cbor.decode(base64.b64decode(self.credential_data))
|
||||
)
|
||||
|
||||
def serialize(self):
|
||||
return {
|
||||
'name': self.name,
|
||||
'credential_data': self.credential_data,
|
||||
'registration_response': self.registration_response,
|
||||
}
|
||||
|
||||
@@ -199,5 +199,15 @@ class UserApiClient(NotifyAdminAPIClient):
|
||||
'created_at': datetime.now().strftime("%Y-%m-%dT%H:%M:%S.%fZ")
|
||||
}]
|
||||
|
||||
def create_webauthn_credential_for_user(self, user_id, credential):
|
||||
self.credentials = getattr(self, 'credentials', [])
|
||||
credential_dict = credential.serialize()
|
||||
|
||||
# TODO: remove when using real API
|
||||
from datetime import datetime
|
||||
credential_dict['created_at'] = datetime.now().strftime("%Y-%m-%dT%H:%M:%S.%fZ")
|
||||
|
||||
self.credentials += [credential_dict]
|
||||
|
||||
|
||||
user_api_client = UserApiClient()
|
||||
|
||||
@@ -51,6 +51,7 @@
|
||||
"classes": "govuk-button--secondary",
|
||||
"attributes": {
|
||||
"data-module": "register-security-key",
|
||||
"data-csrf-token": csrf_token(),
|
||||
}
|
||||
}) }}
|
||||
</div>
|
||||
|
||||
32
app/webauthn_server.py
Normal file
32
app/webauthn_server.py
Normal file
@@ -0,0 +1,32 @@
|
||||
from urllib.parse import urlparse
|
||||
|
||||
from fido2.server import Fido2Server
|
||||
from fido2.webauthn import PublicKeyCredentialRpEntity
|
||||
|
||||
|
||||
def init_app(app):
|
||||
base_url = urlparse(app.config["ADMIN_BASE_URL"])
|
||||
verify_origin_callback = None
|
||||
|
||||
# stub verification in dev (to avoid need for HTTPS)
|
||||
if app.config["NOTIFY_ENVIRONMENT"] == "development":
|
||||
verify_origin_callback = stub_origin_checker
|
||||
|
||||
relying_party = PublicKeyCredentialRpEntity(
|
||||
id=base_url.hostname,
|
||||
name="GOV.UK Notify",
|
||||
)
|
||||
|
||||
app.webauthn_server = Fido2Server(
|
||||
relying_party,
|
||||
attestation="direct",
|
||||
verify_origin=verify_origin_callback,
|
||||
)
|
||||
|
||||
# some browsers don't seem to have a default timeout
|
||||
# 30 seconds seems like a generous amount of time
|
||||
app.webauthn_server.timeout = 30_000
|
||||
|
||||
|
||||
def stub_origin_checker(*args):
|
||||
return True
|
||||
Reference in New Issue
Block a user