Files
Maven/cmd/mavweb/webauthn.go
T
kami 7ab9b48259 coldstart: recover v1 boxes, and make key wrapping an explicit act
Three ways the cold-start path could lose the database.

A box enrolled before the PRF change could never cold-start again. UnwrapKey
still read v1 blobs, but the only caller stopped supplying the v1 secret: the
assertion handler sends the PRF output and nothing looks up the credential
public key any more. On such a box the daemon read the blob, took the v1
branch, failed to decrypt, and stayed locked while a valid passkey was
asserted at it. The escape hatch was gone too, because WrapKeyFn was wired
only in env-key mode and a locked boot is by definition the mode with no env
key. The recovery was to put MAVEN_DB_KEY back in the environment, which is
the thing cold-start unlock exists to avoid. AssertFinish now retries a failed
PRF unwrap with the credential public key, and WrapKeyFn is wired in locked
mode too, so the box that came up on a v1 blob can be moved to v2.

Wrapping ran on every successful assertion. That made a routine step-up
rewrite the one file that opens the database, under whatever 32 bytes the page
posted. A compromised /auth/webauthn converted one legitimate touch into
permanent offline recovery of the at-rest key, and a second enrolled
authenticator silently locked out the first. Wrapping is now an act of its
own: a plain assertion may write the blob only when none exists, and replacing
one takes the rewrite button, which is the only caller that sets the new
explicit flag. The daemon still refuses to overwrite a v2 blob that does not
open under the presented secret.

The write was os.WriteFile, which truncates in place. A power cut between the
truncate and the write left a zero-length blob and no previous contents, on
the path of every step-up. It is now a temp file in the same directory, fsync,
rename, fsync of the directory.

Two smaller things on the same path. The v2 unwrap checked the secret length
but not the all-zero case the wrap side rejects, so the two ends disagreed
about what a valid secret is. And the handler logged "daemon unlocked via
credential" when an env-key daemon had answered unknown method, and again when
an already-unlocked daemon had done nothing.

Left alone deliberately: the PRF value is client-supplied and not covered by
the assertion signature. That is inherent to PRF key wrapping, since the salt
has to be fixed for the blob to open on the next boot. It is recorded as a
known property where the secret enters the handler.

Found in review of #77.
2026-08-01 14:05:13 +04:00

341 lines
15 KiB
Go

package main
import (
"context"
"encoding/json"
"errors"
"fmt"
"log"
"net/http"
"time"
"github.com/kami/maven/internal/auth"
"github.com/kami/maven/internal/ipc"
"github.com/kami/maven/internal/webauthn"
)
// assertIPC — satisfies the AssertStepUp caller shape. The only implementation
// is *ipc.Client; in-process CoreAPI adapters return ErrUnknownMethod.
type assertIPC interface {
AssertStepUp(ctx context.Context) error
}
// keyIPC — satisfies the key-wrap and unlock methods. The only implementation
// is *ipc.Client; in-process CoreAPI adapters do not implement it. When nil,
// StoreEncryptionKey and Unlock are silently skipped.
type keyIPC interface {
StoreEncryptionKey(ctx context.Context, secret []byte, explicit bool) error
Unlock(ctx context.Context, secret []byte) error
}
// PasskeyHandle holds the WebAuthn relying party, a local in-memory credential
// store, and the IPC client used to assert step-up and to wrap/unwrap the
// daemon's encryption key. It serves the four WebAuthn HTTP endpoints
// (register/begin, register/finish, assert/begin, assert/finish).
//
// Credentials are kept in-memory only (a single-user daemon restarts
// infrequently, and re-enrolling after restart is acceptable). A future
// version may persist them to disk.
type PasskeyHandle struct {
rp *webauthn.RP
assertFn assertIPC // *ipc.Client when connected; nil ⇒ no step-up IPC
encryptFn keyIPC // *ipc.Client when connected; nil ⇒ key wrap/unlock disabled
store *credentialStore
session *webauthn.PasskeySession
}
type localCred struct {
PublicKey []byte
SignCount int64
}
func newPasskeyHandle(cfg webauthn.Config, core ipc.CoreAPI, storePath string, session *webauthn.PasskeySession) (*PasskeyHandle, error) {
var af assertIPC
if c, ok := core.(assertIPC); ok {
af = c
}
var ek keyIPC
if c, ok := core.(keyIPC); ok {
ek = c
}
store, err := newCredentialStore(storePath)
if err != nil {
return nil, fmt.Errorf("credential store: %w", err)
}
return &PasskeyHandle{
rp: webauthn.NewRP(cfg),
assertFn: af,
encryptFn: ek,
store: store,
session: session,
}, nil
}
// Page serves the passkey enrollment + step-up UI. It's the only surface that
// can perform a WebAuthn gesture, so it's the gate the /tools enable depends
// on: assert here (bumps the daemon session to L3 for the assertion TTL), then
// enable a tool on /tools within that window.
func (h *PasskeyHandle) Page(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "text/html; charset=utf-8")
passkeyTmpl.Execute(w, nil)
}
// passkeyPageHTML — rendered via passkeyTmpl (main.go) which wraps with shellTop/shellBottom.
const passkeyPageHTML = `{{template "shellTop" "passkey"}}
<h1>Passkey</h1>
<p class=hint>Enroll a passkey once, then assert it to unlock destructive actions (tool enable) for a few minutes.</p>
<div class=flex gap-2>
<button class=btn onclick=enroll()>enroll passkey</button>
<button class=btn onclick=assert()>assert (step-up)</button>
<button class=btn onclick=rewrapKey()>rewrite cold-start key</button>
<a href=/tools><button class=btn-primary>→ tools</button></a>
</div>
<p class=hint>Rewriting the cold-start key points it at the passkey you assert next. Every other enrolled passkey stops being able to unlock a cold-booted daemon.</p>
<div id=msg></div>
{{template "shellBottom"}}
<script>
const b64u=b=>btoa(String.fromCharCode(...new Uint8Array(b))).replace(/\+/g,'-').replace(/\//g,'_').replace(/=+$/,'');
const ub64=s=>{s=s.replace(/-/g,'+').replace(/_/g,'/');const b=atob(s),a=new Uint8Array(b.length);for(let i=0;i<b.length;i++)a[i]=b.charCodeAt(i);return a;};
const say=(t,ok)=>{const m=document.getElementById('msg');m.textContent=t;m.className=ok?'msg msg-ok':'msg msg-err';};
async function enroll(){try{
const {challenge,options}=await (await fetch('/auth/webauthn/register/begin')).json();
options.challenge=ub64(options.challenge);
options.user.id=ub64(options.user.id);
const c=await navigator.credentials.create({publicKey:options});
const r=await fetch('/auth/webauthn/register/finish',{method:'POST',headers:{'content-type':'application/json'},
body:JSON.stringify({challenge,credential:{id:c.id,type:c.type,response:{
clientDataJSON:b64u(c.response.clientDataJSON),attestationObject:b64u(c.response.attestationObject)}}})});
if(!r.ok){say('enroll failed: '+await r.text(),false);return;}
// The wrapped key can only be written from an assertion: PRF results are
// not produced at create() time on most authenticators. Enrolment reports
// whether PRF is available at all so he is not told cold-start works when
// it cannot.
const ext=c.getClientExtensionResults?c.getClientExtensionResults():{};
const prfOK=!!(ext.prf&&ext.prf.enabled);
say(prfOK?'enrolled ✓ — now assert once to write the cold-start key':
'enrolled ✓ — but this authenticator has no PRF: cold-start unlock unavailable',true);
}catch(e){say('enroll error: '+e,false);}}
async function assert(explicit){try{
const {challenge,options}=await (await fetch('/auth/webauthn/assert/begin')).json();
options.challenge=ub64(options.challenge);
const c=await navigator.credentials.get({publicKey:options});
// The PRF result is the cold-start secret. It never touches localStorage
// and is posted once, over the same request as the assertion.
const ext=c.getClientExtensionResults?c.getClientExtensionResults():{};
const prf=ext.prf&&ext.prf.results&&ext.prf.results.first?b64u(ext.prf.results.first):'';
const r=await fetch('/auth/webauthn/assert/finish',{method:'POST',headers:{'content-type':'application/json'},
body:JSON.stringify({challenge,prf,explicit:!!explicit,credential:{id:c.id,type:c.type,response:{
clientDataJSON:b64u(c.response.clientDataJSON),authenticatorData:b64u(c.response.authenticatorData),
signature:b64u(c.response.signature)}}})});
if(!r.ok){say('assert failed: '+await r.text(),false);return;}
if(!prf){say('stepped up ✓ — no PRF from this authenticator, so cold-start unlock stayed unavailable',true);return;}
say(explicit?'stepped up ✓ — cold-start key now points at this passkey':
'stepped up ✓ — enable tools now',true);
}catch(e){say('assert error: '+e,false);}}
// Rewriting the wrapped key is a separate gesture, never a side effect of a
// step-up. Only this button sets explicit, and only explicit lets the daemon
// replace a blob that already exists.
async function rewrapKey(){
if(!confirm('Rewrite the cold-start key under the passkey you are about to assert? Every other enrolled passkey stops being able to unlock a cold-booted daemon.'))return;
await assert(true);}
</script>`
func (h *PasskeyHandle) RegisterBegin(w http.ResponseWriter, r *http.Request) {
opts, challenge, err := h.rp.CreationOptions([]byte("maven-user"), "maven user")
if err != nil {
log.Printf("webauthn: register begin: %v", err)
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(map[string]any{"challenge": challenge, "options": opts})
}
func (h *PasskeyHandle) RegisterFinish(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost {
http.Error(w, "POST only", http.StatusMethodNotAllowed)
return
}
var body struct {
Challenge string `json:"challenge"`
Credential map[string]any `json:"credential"`
}
if err := json.NewDecoder(r.Body).Decode(&body); err != nil {
http.Error(w, "bad request: "+err.Error(), http.StatusBadRequest)
return
}
save := func(id string, publicKey []byte, _ []byte, _ string) error {
return h.store.Save(id, publicKey)
}
credID, err := h.rp.FinishRegistration(save, body.Challenge, body.Credential)
if err != nil {
log.Printf("webauthn: register finish: %v", err)
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
log.Printf("webauthn: registered credential %s", credID)
// Note what does NOT happen here: the encryption key is not wrapped at
// enrolment. Wrapping needs the authenticator's PRF output, and create()
// does not produce one on most authenticators — it only reports whether
// the extension is supported. The wrapped key is written on the first
// assertion instead (see AssertFinish).
//
// This used to wrap the key under the credential *public* key, which is
// written to passkeys.json next to the wrapped blob. See the header of
// internal/webauthn/keywrap.go.
json.NewEncoder(w).Encode(map[string]string{"credential_id": credID})
}
func (h *PasskeyHandle) AssertBegin(w http.ResponseWriter, r *http.Request) {
opts, challenge, err := h.rp.AssertionOptions()
if err != nil {
log.Printf("webauthn: assert begin: %v", err)
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(map[string]any{"challenge": challenge, "options": opts})
}
func (h *PasskeyHandle) AssertFinish(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost {
http.Error(w, "POST only", http.StatusMethodNotAllowed)
return
}
var body struct {
Challenge string `json:"challenge"`
Credential map[string]any `json:"credential"`
// PRF is the base64url WebAuthn PRF output the browser read out of
// getClientExtensionResults(). Empty when the authenticator has no
// PRF extension: cold-start unlock is then unavailable and we say so
// rather than falling back to something weaker.
//
// Known property, accepted deliberately: this value is supplied by
// the client and is NOT covered by the assertion signature. WebAuthn
// client extension outputs never are, and binding one would need a
// per-assertion salt, which would make the wrapped blob unopenable on
// the next boot. Nothing here can tell a real PRF output from 32
// bytes a compromised page chose. What limits the damage is that the
// daemon refuses to rewrite an existing blob unless the operator
// asked for it — see Explicit below and cmd/mavend/keyfile.go.
PRF string `json:"prf"`
// Explicit marks the "rewrite cold-start key" button rather than a
// plain step-up. Only then may the daemon replace a blob that is
// already on disk.
Explicit bool `json:"explicit"`
}
if err := json.NewDecoder(r.Body).Decode(&body); err != nil {
http.Error(w, "bad request: "+err.Error(), http.StatusBadRequest)
return
}
lookup := func(id string) ([]byte, int64, error) {
return h.store.Lookup(id)
}
update := func(id string, count int64) error {
return h.store.UpdateSignCount(id, count)
}
credID, err := h.rp.FinishAssertion(lookup, update, body.Challenge, body.Credential)
if err != nil {
log.Printf("webauthn: assert finish: %v", err)
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
// Assert step-up on the IPC (mavend) side so subsequent EnableTool calls
// see L3. Best-effort: if IPC fails (no -core or mavend unreachable), the
// user still sees success but the enable will fail with AuthStepUp.
if h.assertFn != nil {
ctx, cancel := context.WithTimeout(r.Context(), 5*time.Second)
defer cancel()
if err := h.assertFn.AssertStepUp(ctx); err != nil {
log.Printf("webauthn: assert step-up: %v", err)
http.Error(w, "step-up assertion failed", http.StatusBadGateway)
return
}
}
// Cold-start unlock and key wrapping, both keyed on the PRF secret this
// assertion just produced. The secret is used here and dropped; it is
// never stored on this side, and it must never be logged — unlike a
// signature it does not expire, so one copy in a proxy log or a HAR file
// is permanent access to the wrapped blob.
//
// Order matters: unlock first (if the daemon is locked there is nothing to
// wrap yet), then wrap. Both are best-effort, because the assertion itself
// is valid either way.
if h.encryptFn != nil {
if secret, err := webauthn.DecodePRFResult(body.PRF); err != nil {
log.Printf("webauthn: no usable PRF secret from credential %s: %v", credID, err)
} else {
ctx, cancel := context.WithTimeout(r.Context(), 10*time.Second)
defer cancel()
h.coldStart(ctx, credID, secret, body.Explicit)
}
}
// Assert the in-process session so the POST /tools handler sees step-up.
if h.session != nil {
h.session.Assert(r.Context(), auth.Scope{})
}
log.Printf("webauthn: asserted credential %s", credID)
json.NewEncoder(w).Encode(map[string]string{"credential_id": credID})
}
// coldStart unlocks a locked daemon with this assertion's PRF output and then
// asks it to wrap the at-rest key. Never fatal: a locked or unreachable daemon
// does not invalidate the step-up.
//
// # The legacy retry
//
// A box enrolled before Vikunja #14 has a v1 blob, wrapped under the
// credential PUBLIC key. The PRF secret cannot open it, and this handler is
// the only caller of Unlock, so without a second attempt that box could never
// cold-start again: it would sit locked while a perfectly good passkey was
// asserted, and the only way back in would be putting MAVEN_DB_KEY into the
// environment — the exact thing cold-start unlock exists to avoid.
//
// So a failed PRF unlock is retried with the public key from the credential
// store. That is not a weaker fallback being offered to new deployments:
// nothing writes v1 any more, and a v2 blob does not open under a public key
// either. It is a one-way door out of the old format, and the operator is told
// to walk through it.
func (h *PasskeyHandle) coldStart(ctx context.Context, credID string, secret []byte, explicit bool) {
legacy := false
err := h.encryptFn.Unlock(ctx, secret)
if err != nil && !errors.Is(err, ipc.ErrUnknownMethod) {
if pub, _, lerr := h.store.Lookup(credID); lerr == nil && len(pub) > 0 {
if err2 := h.encryptFn.Unlock(ctx, pub); err2 == nil {
err, legacy = nil, true
}
}
}
switch {
case errors.Is(err, ipc.ErrUnknownMethod):
// Env-key mode: the daemon was never locked and has no UnlockFn. Not
// a failure, and the old code logged it as one on every assertion.
case err != nil:
log.Printf("webauthn: unlock via credential %s failed: %v", credID, err)
case legacy:
log.Printf("SECURITY: webauthn: daemon unlocked from a LEGACY v1 wrapped key using credential %s. That blob is derived from the credential public key, which sits in passkeys.json beside it, so it protects nothing. Press \"rewrite cold-start key\" on this page to replace it with a v2 blob.", credID)
default:
log.Printf("webauthn: daemon reports unlocked, credential %s", credID)
}
// explicit=false means "write the blob only if there is none". The daemon
// enforces that; sending the flag is the whole of this side's part in it.
switch err := h.encryptFn.StoreEncryptionKey(ctx, secret, explicit); {
case err == nil && explicit:
log.Printf("webauthn: cold-start key rewritten under credential %s", credID)
case err == nil:
case errors.Is(err, ipc.ErrUnknownMethod):
// No key to wrap: a plaintext dev store, or a daemon still locked.
default:
log.Printf("webauthn: wrap encryption key: %v", err)
}
}