stages/authenticator_validate: implement validation, add button to go back to device picker

This commit is contained in:
Jens Langhammer 2021-02-25 12:06:05 +01:00
parent 007676b400
commit 0f169f176d
8 changed files with 146 additions and 103 deletions

View File

@ -18,8 +18,6 @@ class ChannelsStorage(FallbackStorage):
def _store(self, messages: list[Message], response, *args, **kwargs): def _store(self, messages: list[Message], response, *args, **kwargs):
prefix = f"user_{self.request.session.session_key}_messages_" prefix = f"user_{self.request.session.session_key}_messages_"
keys = cache.keys(f"{prefix}*") keys = cache.keys(f"{prefix}*")
if len(keys) < 1:
return super()._store(messages, response, *args, **kwargs)
for key in keys: for key in keys:
uid = key.replace(prefix, "") uid = key.replace(prefix, "")
for message in messages: for message in messages:
@ -32,4 +30,3 @@ class ChannelsStorage(FallbackStorage):
"message": message.message, "message": message.message,
}, },
) )
return None

View File

@ -17,7 +17,6 @@ from webauthn.webauthn import (
from authentik.core.models import User from authentik.core.models import User
from authentik.lib.templatetags.authentik_utils import avatar from authentik.lib.templatetags.authentik_utils import avatar
from authentik.stages.authenticator_validate.models import DeviceClasses
from authentik.stages.authenticator_webauthn.models import WebAuthnDevice from authentik.stages.authenticator_webauthn.models import WebAuthnDevice
from authentik.stages.authenticator_webauthn.utils import generate_challenge from authentik.stages.authenticator_webauthn.utils import generate_challenge
@ -70,35 +69,19 @@ def get_webauthn_challenge(request: HttpRequest, device: WebAuthnDevice) -> dict
return webauthn_assertion_options.assertion_dict return webauthn_assertion_options.assertion_dict
def validate_challenge( def validate_challenge_code(code: str, request: HttpRequest, user: User) -> str:
challenge: DeviceChallenge, request: HttpRequest, user: User
) -> DeviceChallenge:
"""main entry point for challenge validation"""
if challenge.validated_data["device_class"] in (
DeviceClasses.TOTP,
DeviceClasses.STATIC,
):
return validate_challenge_code(challenge, request, user)
return validate_challenge_webauthn(challenge, request, user)
def validate_challenge_code(
challenge: DeviceChallenge, request: HttpRequest, user: User
) -> DeviceChallenge:
"""Validate code-based challenges. We test against every device, on purpose, as """Validate code-based challenges. We test against every device, on purpose, as
the user mustn't choose between totp and static devices.""" the user mustn't choose between totp and static devices."""
device = match_token(user, challenge.validated_data["challenge"].get("code", None)) device = match_token(user, code)
if not device: if not device:
raise ValidationError(_("Invalid Token")) raise ValidationError(_("Invalid Token"))
return challenge return code
def validate_challenge_webauthn( def validate_challenge_webauthn(data: dict, request: HttpRequest, user: User) -> dict:
challenge: DeviceChallenge, request: HttpRequest, user: User
) -> DeviceChallenge:
"""Validate WebAuthn Challenge""" """Validate WebAuthn Challenge"""
challenge = request.session.get("challenge") challenge = request.session.get("challenge")
assertion_response = challenge.validated_data["challenge"] assertion_response = data["challenge"]
credential_id = assertion_response.get("id") credential_id = assertion_response.get("id")
device = WebAuthnDevice.objects.filter(credential_id=credential_id).first() device = WebAuthnDevice.objects.filter(credential_id=credential_id).first()
@ -134,4 +117,4 @@ def validate_challenge_webauthn(
raise ValidationError("Assertion failed") from exc raise ValidationError("Assertion failed") from exc
device.set_sign_count(sign_count) device.set_sign_count(sign_count)
return challenge return data

View File

@ -1,11 +1,10 @@
"""Authenticator Validation""" """Authenticator Validation"""
from django.http import HttpRequest, HttpResponse from django.http import HttpRequest, HttpResponse
from django.http.request import QueryDict
from django_otp import devices_for_user from django_otp import devices_for_user
from rest_framework.fields import ListField from rest_framework.fields import CharField, JSONField, ListField
from rest_framework.serializers import ValidationError
from structlog.stdlib import get_logger from structlog.stdlib import get_logger
from authentik.core.models import User
from authentik.flows.challenge import ( from authentik.flows.challenge import (
ChallengeResponse, ChallengeResponse,
ChallengeTypes, ChallengeTypes,
@ -17,15 +16,17 @@ from authentik.flows.stage import ChallengeStageView
from authentik.stages.authenticator_validate.challenge import ( from authentik.stages.authenticator_validate.challenge import (
DeviceChallenge, DeviceChallenge,
get_challenge_for_device, get_challenge_for_device,
validate_challenge, validate_challenge_code,
validate_challenge_webauthn,
)
from authentik.stages.authenticator_validate.models import (
AuthenticatorValidateStage,
DeviceClasses,
) )
from authentik.stages.authenticator_validate.models import AuthenticatorValidateStage, DeviceClasses
LOGGER = get_logger() LOGGER = get_logger()
PER_DEVICE_CLASSES = [ PER_DEVICE_CLASSES = [DeviceClasses.WEBAUTHN]
DeviceClasses.WEBAUTHN
]
class AuthenticatorChallenge(WithUserInfoChallenge): class AuthenticatorChallenge(WithUserInfoChallenge):
@ -34,15 +35,46 @@ class AuthenticatorChallenge(WithUserInfoChallenge):
device_challenges = ListField(child=DeviceChallenge()) device_challenges = ListField(child=DeviceChallenge())
class AuthenticatorChallengeResponse(ChallengeResponse, DeviceChallenge): class AuthenticatorChallengeResponse(ChallengeResponse):
"""Challenge used for Code-based authenticators""" """Challenge used for Code-based and WebAuthn authenticators"""
request: HttpRequest code = CharField(required=False)
user: User webauthn = JSONField(required=False)
def validate_challenge(self, value: dict): def validate_code(self, code: str) -> str:
"""Validate response""" """Validate code-based response, raise error if code isn't allowed"""
return validate_challenge(value, self.request, self.user) device_challenges: list[dict] = self.stage.request.session.get(
"device_challenges"
)
if not any(
x["device_class"] in (DeviceClasses.TOTP, DeviceClasses.STATIC)
for x in device_challenges
):
raise ValidationError("Got code but no compatible device class allowed")
return validate_challenge_code(
code, self.stage.request, self.stage.get_pending_user()
)
def validate_webauthn(self, webauthn: dict) -> dict:
"""Validate webauthn response, raise error if webauthn wasn't allowed
or response is invalid"""
device_challenges: list[dict] = self.stage.request.session.get(
"device_challenges"
)
if not any(
x["device_class"] in (DeviceClasses.WEBAUTHN) for x in device_challenges
):
raise ValidationError("Got webauthn but no compatible device class allowed")
return validate_challenge_webauthn(
webauthn, self.stage.request, self.stage.get_pending_user()
)
def validate(self, data: dict):
# Checking if the given data is from a valid device class is done above
# Here we only check if the any data was sent at all
if "code" not in data and "webauthn" not in data:
raise ValidationError("Empty response")
return data
class AuthenticatorValidateStageView(ChallengeStageView): class AuthenticatorValidateStageView(ChallengeStageView):
@ -51,6 +83,7 @@ class AuthenticatorValidateStageView(ChallengeStageView):
response_class = AuthenticatorChallengeResponse response_class = AuthenticatorChallengeResponse
def get_device_challenges(self) -> list[dict]: def get_device_challenges(self) -> list[dict]:
"""Get a list of all device challenges applicable for the current stage"""
challenges = [] challenges = []
user_devices = devices_for_user(self.get_pending_user()) user_devices = devices_for_user(self.get_pending_user())
@ -112,14 +145,9 @@ class AuthenticatorValidateStageView(ChallengeStageView):
} }
) )
def get_response_instance(self, data: QueryDict) -> ChallengeResponse: # pylint: disable=unused-argument
response: AuthenticatorChallengeResponse = super().get_response_instance(data)
response.request = self.request
response.user = self.get_pending_user()
return response
def challenge_valid( def challenge_valid(
self, challenge: AuthenticatorChallengeResponse self, challenge: AuthenticatorChallengeResponse
) -> HttpResponse: ) -> HttpResponse:
print(challenge) # All validation is done by the serializer
return HttpResponse() return self.executor.stage_ok()

View File

@ -18,7 +18,11 @@ from authentik.flows.planner import PLAN_CONTEXT_PENDING_USER
from authentik.flows.stage import ChallengeStageView from authentik.flows.stage import ChallengeStageView
from authentik.lib.templatetags.authentik_utils import avatar from authentik.lib.templatetags.authentik_utils import avatar
from authentik.stages.authenticator_webauthn.models import WebAuthnDevice from authentik.stages.authenticator_webauthn.models import WebAuthnDevice
from authentik.stages.authenticator_webauthn.utils import generate_challenge, get_origin, get_rp_id from authentik.stages.authenticator_webauthn.utils import (
generate_challenge,
get_origin,
get_rp_id,
)
RP_NAME = "authentik" RP_NAME = "authentik"

View File

@ -1,6 +1,7 @@
"""webauthn utils""" """webauthn utils"""
import base64 import base64
import os import os
from django.http import HttpRequest from django.http import HttpRequest
CHALLENGE_DEFAULT_BYTE_LEN = 32 CHALLENGE_DEFAULT_BYTE_LEN = 32
@ -23,6 +24,7 @@ def generate_challenge(challenge_len=CHALLENGE_DEFAULT_BYTE_LEN):
challenge_base64 = challenge_base64.decode("utf-8") challenge_base64 = challenge_base64.decode("utf-8")
return challenge_base64 return challenge_base64
def get_rp_id(request: HttpRequest) -> str: def get_rp_id(request: HttpRequest) -> str:
"""Get hostname from http request, without port""" """Get hostname from http request, without port"""
host = request.get_host() host = request.get_host()
@ -30,6 +32,7 @@ def get_rp_id(request: HttpRequest) -> str:
return host.split(":")[0] return host.split(":")[0]
return host return host
def get_origin(request: HttpRequest) -> str: def get_origin(request: HttpRequest) -> str:
"""Return Origin by building an absolute URL and removing the """Return Origin by building an absolute URL and removing the
trailing slash""" trailing slash"""

View File

@ -23,7 +23,8 @@ export interface AuthenticatorValidateStageChallenge extends WithUserInfoChallen
} }
export interface AuthenticatorValidateStageChallengeResponse { export interface AuthenticatorValidateStageChallengeResponse {
response: DeviceChallenge; code: string;
webauthn: string;
} }
@customElement("ak-stage-authenticator-validate") @customElement("ak-stage-authenticator-validate")
@ -145,13 +146,15 @@ export class AuthenticatorValidateStage extends BaseStage implements StageHost {
${gettext("Select an identification method.")} ${gettext("Select an identification method.")}
</p>`} </p>`}
</header> </header>
<div class="pf-c-login__main-body"> ${this.selectedDeviceChallenge ?
${this.selectedDeviceChallenge ? this.renderDeviceChallenge() : this.renderDevicePicker()} this.renderDeviceChallenge() :
</div> html`<div class="pf-c-login__main-body">
<footer class="pf-c-login__main-footer"> ${this.renderDevicePicker()}
<ul class="pf-c-login__main-footer-links"> </div>
</ul> <footer class="pf-c-login__main-footer">
</footer>`; <ul class="pf-c-login__main-footer-links">
</ul>
</footer>`}`;
} }
} }

View File

@ -2,7 +2,8 @@ import { gettext } from "django";
import { CSSResult, customElement, html, property, TemplateResult } from "lit-element"; import { CSSResult, customElement, html, property, TemplateResult } from "lit-element";
import { COMMON_STYLES } from "../../../common/styles"; import { COMMON_STYLES } from "../../../common/styles";
import { BaseStage } from "../base"; import { BaseStage } from "../base";
import { AuthenticatorValidateStageChallenge, DeviceChallenge } from "./AuthenticatorValidateStage"; import { AuthenticatorValidateStage, AuthenticatorValidateStageChallenge, DeviceChallenge } from "./AuthenticatorValidateStage";
import "../form";
@customElement("ak-stage-authenticator-validate-code") @customElement("ak-stage-authenticator-validate-code")
export class AuthenticatorValidateStageWebCode extends BaseStage { export class AuthenticatorValidateStageWebCode extends BaseStage {
@ -21,44 +22,55 @@ export class AuthenticatorValidateStageWebCode extends BaseStage {
if (!this.challenge) { if (!this.challenge) {
return html`<ak-loading-state></ak-loading-state>`; return html`<ak-loading-state></ak-loading-state>`;
} }
return html`<form class="pf-c-form" @submit=${(e: Event) => { this.submitForm(e); }}> return html`<div class="pf-c-login__main-body">
<div class="pf-c-form__group"> <form class="pf-c-form" @submit=${(e: Event) => { this.submitForm(e); }}>
<div class="form-control-static"> <div class="pf-c-form__group">
<div class="left"> <div class="form-control-static">
<img class="pf-c-avatar" src="${this.challenge.pending_user_avatar}" alt="${gettext("User's avatar")}"> <div class="left">
${this.challenge.pending_user} <img class="pf-c-avatar" src="${this.challenge.pending_user_avatar}" alt="${gettext("User's avatar")}">
</div> ${this.challenge.pending_user}
<div class="right"> </div>
<a href="/flows/-/cancel/">${gettext("Not you?")}</a> <div class="right">
</div> <a href="/flows/-/cancel/">${gettext("Not you?")}</a>
</div> </div>
</div> </div>
<input type="hidden" name="device_class" value=${this.deviceChallenge?.device_class}> </div>
<input type="hidden" name="device_uid" value=${this.deviceChallenge?.device_uid}> <ak-form-element
label="${gettext("Code")}"
?required="${true}"
class="pf-c-form__group"
.errors=${(this.challenge?.response_errors || {})["code"]}>
<!-- @ts-ignore -->
<input type="text"
name="code"
inputmode="numeric"
pattern="[0-9]*"
placeholder="${gettext("Please enter your TOTP Code")}"
autofocus=""
autocomplete="one-time-code"
class="pf-c-form-control"
required="">
</ak-form-element>
<ak-form-element <div class="pf-c-form__group pf-m-action">
label="${gettext("Code")}" <button type="submit" class="pf-c-button pf-m-primary pf-m-block">
?required="${true}" ${gettext("Continue")}
class="pf-c-form__group" </button>
.errors=${(this.challenge?.response_errors || {})["code"]}> </div>
<!-- @ts-ignore --> </form>
<input type="text" </div>
name="challenge" <footer class="pf-c-login__main-footer">
inputmode="numeric" <ul class="pf-c-login__main-footer-links">
pattern="[0-9]*" <li class="pf-c-login__main-footer-links-item">
placeholder="${gettext("Please enter your TOTP Code")}" <button class="pf-c-button pf-m-secondary pf-m-block" @click=${() => {
autofocus="" if (!this.host) return;
autocomplete="one-time-code" (this.host as AuthenticatorValidateStage).selectedDeviceChallenge = undefined;
class="pf-c-form-control" }}>
required=""> ${gettext("Return to device picker")}
</ak-form-element> </button>
</li>
<div class="pf-c-form__group pf-m-action"> </ul>
<button type="submit" class="pf-c-button pf-m-primary pf-m-block"> </footer>`;
${gettext("Continue")}
</button>
</div>
</form>`;
} }
} }

View File

@ -1,9 +1,10 @@
import { gettext } from "django"; import { gettext } from "django";
import { customElement, html, property, TemplateResult } from "lit-element"; import { CSSResult, customElement, html, property, TemplateResult } from "lit-element";
import { COMMON_STYLES } from "../../../common/styles";
import { SpinnerSize } from "../../Spinner"; import { SpinnerSize } from "../../Spinner";
import { transformAssertionForServer, transformCredentialRequestOptions } from "../authenticator_webauthn/utils"; import { transformAssertionForServer, transformCredentialRequestOptions } from "../authenticator_webauthn/utils";
import { BaseStage } from "../base"; import { BaseStage } from "../base";
import { AuthenticatorValidateStageChallenge, DeviceChallenge } from "./AuthenticatorValidateStage"; import { AuthenticatorValidateStage, AuthenticatorValidateStageChallenge, DeviceChallenge } from "./AuthenticatorValidateStage";
@customElement("ak-stage-authenticator-validate-webauthn") @customElement("ak-stage-authenticator-validate-webauthn")
export class AuthenticatorValidateStageWebAuthn extends BaseStage { export class AuthenticatorValidateStageWebAuthn extends BaseStage {
@ -20,6 +21,10 @@ export class AuthenticatorValidateStageWebAuthn extends BaseStage {
@property() @property()
authenticateMessage = ""; authenticateMessage = "";
static get styles(): CSSResult[] {
return COMMON_STYLES;
}
async authenticate(): Promise<void> { async authenticate(): Promise<void> {
// convert certain members of the PublicKeyCredentialRequestOptions into // convert certain members of the PublicKeyCredentialRequestOptions into
// byte arrays as expected by the spec. // byte arrays as expected by the spec.
@ -47,11 +52,7 @@ export class AuthenticatorValidateStageWebAuthn extends BaseStage {
// post the assertion to the server for verification. // post the assertion to the server for verification.
try { try {
const formData = new FormData(); const formData = new FormData();
formData.set("response", JSON.stringify(<DeviceChallenge>{ formData.set("webauthn", JSON.stringify(transformedAssertionForServer));
device_class: this.deviceChallenge?.device_class,
device_uid: this.deviceChallenge?.device_uid,
challenge: transformedAssertionForServer,
}));
await this.host?.submit(formData); await this.host?.submit(formData);
} catch (err) { } catch (err) {
throw new Error(gettext(`Error when validating assertion on server: ${err}`)); throw new Error(gettext(`Error when validating assertion on server: ${err}`));
@ -76,7 +77,7 @@ export class AuthenticatorValidateStageWebAuthn extends BaseStage {
} }
render(): TemplateResult { render(): TemplateResult {
return html`<div class=""> return html`<div class="pf-c-login__main-body">
${this.authenticateRunning ? ${this.authenticateRunning ?
html`<div class="pf-c-empty-state__content"> html`<div class="pf-c-empty-state__content">
<div class="pf-l-bullseye"> <div class="pf-l-bullseye">
@ -94,7 +95,19 @@ export class AuthenticatorValidateStageWebAuthn extends BaseStage {
${gettext("Retry authentication")} ${gettext("Retry authentication")}
</button> </button>
</div>`} </div>`}
</div>`; </div>
<footer class="pf-c-login__main-footer">
<ul class="pf-c-login__main-footer-links">
<li class="pf-c-login__main-footer-links-item">
<button class="pf-c-button pf-m-secondary pf-m-block" @click=${() => {
if (!this.host) return;
(this.host as AuthenticatorValidateStage).selectedDeviceChallenge = undefined;
}}>
${gettext("Return to device picker")}
</button>
</li>
</ul>
</footer>`;
} }
} }