Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 4 additions & 1 deletion DESIGN.md
Original file line number Diff line number Diff line change
Expand Up @@ -5091,7 +5091,10 @@ the fetch happens at the pre-approval, which has no short limit:
TOTP seed) in memory, with the grant of the pre-approval (`internal/broker/remembered.go`). It is
never written to disk or to a log. Without it, no grant starts: at
most `maxRememberedLogins` (64) logins are kept for all clients; one
more pre-approval is denied (cause `limit`, 429).
more pre-approval is denied (cause `limit`, 429). The request keeps a
copy; it clears its own copy of the item it read (the password and
the TOTP seed) before it answers, when it allows and when it denies
(#205).
- The login request that the core allows by that grant gets the login
from memory, with **no run of `bw`**. Before the core decides, the
broker runs every check of 21.3 on the remembered item against the
Expand Down
5 changes: 4 additions & 1 deletion THREAT-MODEL.md
Original file line number Diff line number Diff line change
Expand Up @@ -1641,7 +1641,10 @@ What nodkey does:
the tap on the monotonic clock: a wall clock set back during the fetch
does not make them longer. After a suspend of the host, the login may
stay in memory longer, until the next request or the end of the grant
in the core, but it cannot be used. The TOTP seed is not kept.
in the core, but it cannot be used. The TOTP seed is not kept. The
pre-approval request clears its own copy of the item that it read
after the tap (the password and the seed) before it answers, also when
it denies (#205).
- Logins and pre-approvals have a rate limit per client, before the
store runs.
- A reload keeps a login grant only when the item has the same rule.
Expand Down
21 changes: 16 additions & 5 deletions internal/broker/logins.go
Original file line number Diff line number Diff line change
Expand Up @@ -589,7 +589,7 @@ func (rq *request) sameLogin(page loginmatch.Page, item string, sel loginSel, l
// of now, and hands out its username and password. On a failure the
// request is answered.
func (rq *request) handOutLogin(ctx context.Context, rc receipt, page loginmatch.Page, item string, sel loginSel, l store.Login, from string) {
if !rq.sameLogin(page, item, sel, l, from) || !rq.stillAllowedLogin(sel, item) {
if !rq.sameLogin(page, item, sel, l, from) || !rq.stillAllowedLogin(sel, item, func() {}) {
rq.s.log.Warn("broker: the login item changed while the request waited; the request is denied",
slog.String("request_id", rq.sub.RequestID), slog.String("client", rq.client))
rq.ended = true
Expand Down Expand Up @@ -662,8 +662,12 @@ func (rq *request) fetchApproved(ctx context.Context, item string) (store.Login,

// stillAllowedLogin checks, after the tap, that a reload did not take away
// what the request uses: the client and its pin, and the rule of the item.
func (rq *request) stillAllowedLogin(sel loginSel, item string) bool {
if !rq.stillAllowed(rq.decided, nil, "", nil) {
// When a reload took the client or its pin away, it runs beforeDeny, then
// denies the request and answers.
func (rq *request) stillAllowedLogin(sel loginSel, item string, beforeDeny func()) bool {
if !rq.allowedNow(rq.decided, nil, "", nil) {
beforeDeny()
rq.denyReloaded()
return false // it has answered
}
l, ok := rq.s.view().cfg.Logins[sel.section]
Expand Down Expand Up @@ -960,7 +964,9 @@ func (rq *request) preapproveLogin(ctx context.Context, req *api.PreapproveReque
// monotonic clock; the remembered login ends no later than that. The
// time since the tap includes the fetch.
end := rq.s.nowTime().Add(approval.LoginPreapproveTime - res.SinceTap())
if !rq.sameLogin(page, item, sel, l, from) || !rq.stillAllowedLogin(sel, item) {
// Clear the copy of the request before any answer, as below.
if !rq.sameLogin(page, item, sel, l, from) || !rq.stillAllowedLogin(sel, item, l.Clear) {
l.Clear()
rq.s.log.Warn("broker: the login item changed while the request waited; the pre-approval is denied",
slog.String("request_id", rq.sub.RequestID), slog.String("client", rq.client))
rq.ended = true
Expand All @@ -970,7 +976,12 @@ func (rq *request) preapproveLogin(ctx context.Context, req *api.PreapproveReque
}
sel.meta = l.LoginItem // the item as the login will see it
rem := rememberedLogin{client: rq.client, item: item, origin: origin, from: from, sel: sel, end: end}
if why := rq.s.remember(res.GrantID, rem, l); why != "" {
why := rq.s.remember(res.GrantID, rem, l)
// remember keeps its own copy. Clear this one now, before the answer
// goes out, not after it: once the client has the answer, the broker
// holds only the copy that the login uses or that its end clears.
l.Clear()
if why != "" {
rq.s.log.Warn("broker: the login of a pre-approval cannot be kept, so the pre-approval is denied: "+string(why),
slog.String("request_id", rq.sub.RequestID), slog.String("client", rq.client))
if why == keptNothingStop {
Expand Down
13 changes: 13 additions & 0 deletions internal/broker/logins_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -157,6 +157,19 @@ func (f *fakeLoginStore) checkCleared(t testing.TB) {
}
}

// allCleared reports whether every password and seed that the store gave
// out is cleared now.
func (f *fakeLoginStore) allCleared() bool {
f.lmu.Lock()
defer f.lmu.Unlock()
for _, b := range f.given {
if len(b) > 0 && !bytes.Equal(b, make([]byte, len(b))) {
return false
}
}
return true
}

// runs returns how many fetches and lists ran, and how many of them
// synced.
func (f *fakeLoginStore) runs() (fetches, syncs int) {
Expand Down
19 changes: 15 additions & 4 deletions internal/broker/reload.go
Original file line number Diff line number Diff line change
Expand Up @@ -97,6 +97,15 @@ func sameKey(old, next *view, name string) bool {
// request may not go on, it is denied (cause not_allowed, 403) and the
// broker logs why; it reports false.
func (rq *request) stillAllowed(decided *config.Broker, secrets []string, key string, hostKey []byte) bool {
if rq.allowedNow(decided, secrets, key, hostKey) {
return true
}
rq.denyReloaded()
return false
}

// allowedNow is the check of stillAllowed. It does not answer.
func (rq *request) allowedNow(decided *config.Broker, secrets []string, key string, hostKey []byte) bool {
cur := rq.s.view()
ok := rq.v != nil && decided != nil && rq.hasPin
if ok {
Expand All @@ -122,13 +131,15 @@ func (rq *request) stillAllowed(decided *config.Broker, secrets []string, key st
if ok && key != "" && rq.v != cur {
ok = sameKey(rq.v, cur, key)
}
if ok {
return true
}
return ok
}

// denyReloaded denies the request because a reload took away what it
// uses (stillAllowed): cause not_allowed, 403.
func (rq *request) denyReloaded() {
rq.s.log.Warn("broker: a reload of the config took away what an approved request uses; the request is denied",
slog.String("request_id", rq.sub.RequestID), slog.String("client", rq.client))
rq.ended = true
_, _ = rq.s.append(audit.Denied{Subject: rq.sub, Cause: audit.CauseNotAllowed})
rq.answer(http.StatusForbidden)
return false
}
93 changes: 93 additions & 0 deletions internal/broker/remembered_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ import (
"slices"
"strings"
"sync"
"sync/atomic"
"testing"
"time"

Expand Down Expand Up @@ -631,6 +632,98 @@ func TestLoginRememberedTimer(t *testing.T) {
})
}

// TestLoginPreapproveClearsBeforeTheAnswer: the request of a login
// pre-approval clears its own copy of the login before the answer goes
// out, on the allow path and on the deny paths after the fetch. Only the
// copy of the remembered login stays. Before #205, the copy of the
// request was cleared after the answer, and a check right after the
// answer sometimes found it not cleared.
func TestLoginPreapproveClearsBeforeTheAnswer(t *testing.T) {
t.Run("allowed: before the grant starts", func(t *testing.T) {
l := newLoginEnv(t, nil)
l.svc.setNow(l.clock.Now)
var seen, cleared atomic.Bool
l.svc.startHook = func(point string) {
if point == "before" {
seen.Store(true)
cleared.Store(l.vs.allCleared())
}
}
mustStatus(t, l.loginPre(itemShop, pageShop), http.StatusOK)
if !seen.Load() || !cleared.Load() {
t.Errorf("before the grant started (hook ran: %v), the fetched values were not cleared", seen.Load())
}
if n := l.svc.rememberedCount(); n != 1 {
t.Errorf("the broker keeps %d logins, want 1", n)
}
})
// denied checks that the values are cleared when the denied entry is
// written, before the answer.
denied := func(t *testing.T, l *loginTest, cause audit.Cause, ask func() *result) {
t.Helper()
var seen, cleared atomic.Bool
l.audit.setFail(func(ev audit.Event) error {
// The first entry: it comes before the answer.
if d, is := ev.(audit.Denied); is && d.Cause == cause && seen.CompareAndSwap(false, true) {
cleared.Store(l.vs.allCleared())
}
return nil
})
if res := ask(); res.status == http.StatusOK {
t.Fatal("the pre-approval is allowed")
}
if !seen.Load() || !cleared.Load() {
t.Errorf("when the pre-approval was denied (entry written: %v), the fetched values were not cleared", seen.Load())
}
if n := l.svc.rememberedCount(); n != 0 {
t.Errorf("the broker keeps %d logins", n)
}
}
t.Run("denied: the fetch took too long", func(t *testing.T) {
l := newLoginEnv(t, nil)
l.svc.setNow(l.clock.Now)
l.vs.lmu.Lock()
l.vs.onFetch = func(n int) {
if n == 2 {
l.clock.Advance(61 * time.Second)
}
}
l.vs.lmu.Unlock()
denied(t, l, audit.CauseLimit, func() *result { return l.loginPre(itemShop, pageShop) })
})
t.Run("denied: a reload took the pin away during the fetch", func(t *testing.T) {
l := newLoginEnv(t, nil)
l.vs.lmu.Lock()
l.vs.onFetch = func(n int) {
if n != 2 {
return
}
next := *l.svc.view().cfg
next.Clients = maps.Clone(next.Clients)
c := next.Clients["laptop"]
c.Pin[0] ^= 0xff // another key
next.Clients["laptop"] = c
if _, err := l.svc.Reload(&next, l.svc.view().keys, strings.Repeat("a", 64)); err != nil {
t.Error(err)
}
}
l.vs.lmu.Unlock()
denied(t, l, audit.CauseNotAllowed, func() *result { return l.loginPre(itemShop, pageShop) })
})
t.Run("denied: the item changed during the tap", func(t *testing.T) {
l := newLoginEnv(t, nil)
denied(t, l, audit.CauseNotAllowed, func() *result {
p := l.start(l.laptp, api.PathPreapprove, api.PreapproveRequest{Login: itemShop, URL: pageShop, Uses: 1})
pr := l.waitAsked(1)[0].Prompt
l.vs.lmu.Lock()
l.shop.Username = "mallory@example.com"
l.vs.lmu.Unlock()
l.tap(pr.RequestID, audit.AnswerApproveOnce)
return p.wait(t)
})
})
}

// TestLoginPreapproveWallClockBack: the wall clock is set back by an hour
// during the fetch after the tap. The grant and the remembered login
// still end 60 s after the tap, counted on the monotonic clock.
Expand Down
20 changes: 15 additions & 5 deletions internal/ntfy/approver_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -242,11 +242,21 @@ func TestFloodOfBadAnswers(t *testing.T) {
if n := strings.Count(h.logs.String(), "refused an answer"); n > refusedPerMinute {
t.Errorf("logged %d refused answers, want at most %d", n, refusedPerMinute)
}
h.a.mu.Lock()
n := len(h.a.pending)
h.a.mu.Unlock()
if n != 0 {
t.Errorf("the approver keeps %d values, want 0", n)
// The fake core gives the answer to the test inside answer(), and the
// approver forgets the value only after answer() returns (handle in
// run.go). So wait for it, up to a limit (#205).
deadline := time.Now().Add(10 * time.Second)
for {
h.a.mu.Lock()
n := len(h.a.pending)
h.a.mu.Unlock()
if n == 0 {
break
}
if time.Now().After(deadline) {
t.Fatalf("the approver keeps %d values 10 s after the answer, want 0", n)
}
time.Sleep(5 * time.Millisecond)
}
}

Expand Down
Loading