| 1 | package home |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "crypto/rand" |
| 6 | "database/sql" |
| 7 | "encoding/base32" |
| 8 | "encoding/base64" |
| 9 | "encoding/hex" |
| 10 | "encoding/json" |
| 11 | "net/http" |
| 12 | "strings" |
| 13 | "sync" |
| 14 | "time" |
| 15 | |
| 16 | "amadan.net/rastrillo/rastrillo/sessions" |
| 17 | "amadan.net/rastrillo/rastrillo/webauthn" |
| 18 | "github.com/keymaildev/signin" |
| 19 | ) |
| 20 | |
| 21 | const recoveryCookie = "__Host-oficina-recovery" |
| 22 | const noticeCookie = "__Host-oficina-notice" |
| 23 | |
| 24 | type mailboxProof struct { |
| 25 | subject, address string |
| 26 | expires int64 |
| 27 | } |
| 28 | type mailboxMemory struct { |
| 29 | mu sync.Mutex |
| 30 | entries map[string]mailboxProof |
| 31 | } |
| 32 | |
| 33 | func (m *mailboxMemory) put(key string, p mailboxProof) bool { |
| 34 | m.mu.Lock() |
| 35 | defer m.mu.Unlock() |
| 36 | if m.entries == nil { |
| 37 | m.entries = map[string]mailboxProof{} |
| 38 | } |
| 39 | for k, v := range m.entries { |
| 40 | if v.expires <= time.Now().Unix() { |
| 41 | delete(m.entries, k) |
| 42 | } |
| 43 | } |
| 44 | if len(m.entries) >= 1000 { |
| 45 | return false |
| 46 | } |
| 47 | m.entries[key] = p |
| 48 | time.AfterFunc(time.Until(time.Unix(p.expires, 0)), func() { |
| 49 | m.mu.Lock() |
| 50 | defer m.mu.Unlock() |
| 51 | if v, ok := m.entries[key]; ok && v.expires <= time.Now().Unix() { |
| 52 | delete(m.entries, key) |
| 53 | } |
| 54 | }) |
| 55 | return true |
| 56 | } |
| 57 | func (m *mailboxMemory) get(key string) (mailboxProof, bool) { |
| 58 | m.mu.Lock() |
| 59 | defer m.mu.Unlock() |
| 60 | p, ok := m.entries[key] |
| 61 | if !ok || p.expires <= time.Now().Unix() { |
| 62 | delete(m.entries, key) |
| 63 | return mailboxProof{}, false |
| 64 | } |
| 65 | return p, true |
| 66 | } |
| 67 | func (m *mailboxMemory) remove(key string) { m.mu.Lock(); defer m.mu.Unlock(); delete(m.entries, key) } |
| 68 | |
| 69 | // The verified address enters only this bounded RAM store. A restart asks the |
| 70 | // person to prove the mailbox again; there is no persisted notice retry queue. |
| 71 | func (a *App) idGate(w http.ResponseWriter, r *http.Request, s sessions.Session, address string) (bool, error) { |
| 72 | tx, now, err := a.idTransaction(r.Context()) |
| 73 | if err != nil { |
| 74 | return false, err |
| 75 | } |
| 76 | defer tx.Rollback() |
| 77 | var n int |
| 78 | if err = tx.QueryRow("SELECT count(*) FROM passkey_credentials WHERE subject=?", s.Subject).Scan(&n); err != nil { |
| 79 | return false, errIDProof |
| 80 | } |
| 81 | if n == 0 { |
| 82 | token, e := a.idMint(tx, r, s, now) |
| 83 | if e != nil { |
| 84 | return false, errIDProof |
| 85 | } |
| 86 | if tx.Commit() != nil { |
| 87 | return false, errIDProof |
| 88 | } |
| 89 | idCookie(w, a.sessions.CookieName(), token, 30*24*3600) |
| 90 | http.Redirect(w, r, sessions.SafeReturn(r, "/"), http.StatusSeeOther) |
| 91 | return true, nil |
| 92 | } |
| 93 | token, hash, err := sessions.NewToken() |
| 94 | if err != nil { |
| 95 | return false, errIDProof |
| 96 | } |
| 97 | if _, err = tx.Exec("DELETE FROM passkey_pending WHERE expires_at<=?", time.Unix(now, 0).UTC().Format(time.RFC3339)); err != nil { |
| 98 | return false, errIDProof |
| 99 | } |
| 100 | if err = tx.QueryRow("SELECT count(*) FROM passkey_pending").Scan(&n); err != nil || n >= 10000 { |
| 101 | return false, errIDProof |
| 102 | } |
| 103 | mailboxAt := s.At |
| 104 | if s.Method == string(signin.MethodKeymail) { |
| 105 | mailboxAt = s.AuthTime |
| 106 | } |
| 107 | if !freshGesture(mailboxAt, time.Now(), 5*time.Minute) { |
| 108 | mailboxAt = time.Time{} |
| 109 | } |
| 110 | mailboxUnix := int64(0) |
| 111 | if !mailboxAt.IsZero() { |
| 112 | mailboxUnix = mailboxAt.Unix() |
| 113 | } |
| 114 | if mailboxUnix > 0 && !a.mailboxes.put(hash, mailboxProof{s.Subject, address, mailboxUnix + 300}) { |
| 115 | mailboxUnix = 0 |
| 116 | } |
| 117 | if _, err = tx.Exec("INSERT INTO passkey_pending(token_hash,subject,method,return_to,expires_at,mailbox_at) VALUES(?,?,?,?,?,?)", hash, s.Subject, s.Method, sessions.SafeReturn(r, "/"), time.Unix(now+300, 0).UTC().Format(time.RFC3339), mailboxUnix); err != nil { |
| 118 | return false, errIDProof |
| 119 | } |
| 120 | if err = tx.Commit(); err != nil { |
| 121 | a.mailboxes.remove(hash) |
| 122 | return false, errIDProof |
| 123 | } |
| 124 | idCookie(w, gateCookie, token, 300) |
| 125 | http.Redirect(w, r, confirmPath, http.StatusSeeOther) |
| 126 | return true, nil |
| 127 | } |
| 128 | func normalizeIDCode(code string) string { |
| 129 | return strings.NewReplacer("-", "", " ", "").Replace(strings.ToLower(code)) |
| 130 | } |
| 131 | |
| 132 | // recoveryCodesRemaining counts subject's unspent recovery codes, for the |
| 133 | // "6 of 10 left" page. Home mints and redeems these codes itself (above |
| 134 | // and in idRecovery), so it counts them itself too: passkey's |
| 135 | // RecoveryCodesRemaining moved to rastrillo/secondfactor at v0.27.1, |
| 136 | // which Home does not wire. |
| 137 | func (a *App) recoveryCodesRemaining(subject string) (int, error) { |
| 138 | var n int |
| 139 | err := a.db.Writer().QueryRow("SELECT count(*) FROM passkey_recovery_codes WHERE subject=?", subject).Scan(&n) |
| 140 | return n, err |
| 141 | } |
| 142 | func generateIDCodes(tx *sql.Tx, subject string, now int64) ([]string, error) { |
| 143 | if _, err := tx.Exec("DELETE FROM passkey_recovery_codes WHERE subject=?", subject); err != nil { |
| 144 | return nil, errIDProof |
| 145 | } |
| 146 | codes := make([]string, 10) |
| 147 | for i := range codes { |
| 148 | raw := make([]byte, 16) |
| 149 | if _, err := rand.Read(raw); err != nil { |
| 150 | return nil, errIDProof |
| 151 | } |
| 152 | c := strings.ToLower(base32.StdEncoding.WithPadding(base32.NoPadding).EncodeToString(raw)) |
| 153 | codes[i] = c[:6] + "-" + c[6:12] + "-" + c[12:19] + "-" + c[19:] |
| 154 | if _, err := tx.Exec("INSERT INTO passkey_recovery_codes(code_hash,subject,created_at) VALUES(?,?,?)", sessions.HashToken(normalizeIDCode(c)), subject, time.Unix(now, 0).UTC().Format(time.RFC3339)); err != nil { |
| 155 | return nil, errIDProof |
| 156 | } |
| 157 | } |
| 158 | return codes, nil |
| 159 | } |
| 160 | func (a *App) idRecovery(w http.ResponseWriter, r *http.Request) { |
| 161 | r.Body = http.MaxBytesReader(w, r.Body, 4096) |
| 162 | if r.ParseForm() != nil { |
| 163 | idRefuse(w) |
| 164 | return |
| 165 | } |
| 166 | code := normalizeIDCode(r.PostForm.Get("code")) |
| 167 | tx, now, err := a.idTransaction(r.Context()) |
| 168 | if err != nil { |
| 169 | idRefuse(w) |
| 170 | return |
| 171 | } |
| 172 | defer tx.Rollback() |
| 173 | subject, binding, err := a.idBinding(tx, r, "signin", now) |
| 174 | if err != nil { |
| 175 | idRefuse(w) |
| 176 | return |
| 177 | } |
| 178 | var mailboxAt int64 |
| 179 | if tx.QueryRow("SELECT mailbox_at FROM passkey_pending WHERE token_hash=?", binding).Scan(&mailboxAt) != nil { |
| 180 | idRefuse(w) |
| 181 | return |
| 182 | } |
| 183 | if mailboxAt <= 0 || mailboxAt > now || mailboxAt+300 <= now { |
| 184 | http.Redirect(w, r, "/signin?force=1", http.StatusSeeOther) |
| 185 | return |
| 186 | } |
| 187 | failed := func() { http.Redirect(w, r, confirmPath+"?recovery=failed", http.StatusSeeOther) } |
| 188 | if _, err = tx.Exec("DELETE FROM home_id_attempts WHERE expires_at<=?", now); err != nil { |
| 189 | idRefuse(w) |
| 190 | return |
| 191 | } |
| 192 | buckets := []struct { |
| 193 | key string |
| 194 | limit int |
| 195 | }{{"account:" + subject, 5}, {"ip:" + blindIndex(a.secrets.Pepper, clientIP(r)), 20}} |
| 196 | for _, b := range buckets { |
| 197 | var failures int |
| 198 | err = tx.QueryRow("SELECT failures FROM home_id_attempts WHERE bucket=?", b.key).Scan(&failures) |
| 199 | if err != nil && err != sql.ErrNoRows { |
| 200 | idRefuse(w) |
| 201 | return |
| 202 | } |
| 203 | if failures >= b.limit { |
| 204 | if tx.Commit() != nil { |
| 205 | idRefuse(w) |
| 206 | return |
| 207 | } |
| 208 | failed() |
| 209 | return |
| 210 | } |
| 211 | } |
| 212 | var got string |
| 213 | err = tx.QueryRow("DELETE FROM passkey_recovery_codes WHERE subject=? AND code_hash=? RETURNING subject", subject, sessions.HashToken(code)).Scan(&got) |
| 214 | if err == sql.ErrNoRows { |
| 215 | var n int |
| 216 | if tx.QueryRow("SELECT count(*) FROM home_id_attempts").Scan(&n) != nil || n >= 10000 { |
| 217 | idRefuse(w) |
| 218 | return |
| 219 | } |
| 220 | for _, b := range buckets { |
| 221 | if _, err = tx.Exec("INSERT INTO home_id_attempts VALUES(?,1,?) ON CONFLICT(bucket) DO UPDATE SET failures=failures+1", b.key, now+900); err != nil { |
| 222 | idRefuse(w) |
| 223 | return |
| 224 | } |
| 225 | } |
| 226 | if tx.Commit() != nil { |
| 227 | idRefuse(w) |
| 228 | return |
| 229 | } |
| 230 | failed() |
| 231 | return |
| 232 | } |
| 233 | if err != nil { |
| 234 | idRefuse(w) |
| 235 | return |
| 236 | } |
| 237 | var method, to, expires string |
| 238 | if err = tx.QueryRow("DELETE FROM passkey_pending WHERE token_hash=? RETURNING method,return_to,expires_at", binding).Scan(&method, &to, &expires); err != nil { |
| 239 | idRefuse(w) |
| 240 | return |
| 241 | } |
| 242 | exp, err := time.Parse(time.RFC3339, expires) |
| 243 | if err != nil { |
| 244 | idRefuse(w) |
| 245 | return |
| 246 | } |
| 247 | token, err := a.idMint(tx, r, sessions.Session{Subject: subject, Method: method + "+recovery", AuthTime: time.Unix(now, 0)}, now) |
| 248 | if err != nil { |
| 249 | idRefuse(w) |
| 250 | return |
| 251 | } |
| 252 | proof, hash, err := sessions.NewToken() |
| 253 | if err != nil { |
| 254 | idRefuse(w) |
| 255 | return |
| 256 | } |
| 257 | if _, err = tx.Exec("DELETE FROM home_id_recovery_proofs WHERE expires_at<=?", now); err != nil { |
| 258 | idRefuse(w) |
| 259 | return |
| 260 | } |
| 261 | var proofCount int |
| 262 | if tx.QueryRow("SELECT count(*) FROM home_id_recovery_proofs").Scan(&proofCount) != nil || proofCount >= 10000 { |
| 263 | idRefuse(w) |
| 264 | return |
| 265 | } |
| 266 | if _, err = tx.Exec("INSERT INTO home_id_recovery_proofs VALUES(?,?,?,?)", hash, subject, sessions.HashToken(token), exp.Unix()); err != nil { |
| 267 | idRefuse(w) |
| 268 | return |
| 269 | } |
| 270 | p, ok := a.mailboxes.get(binding) |
| 271 | if !ok || p.subject != subject || !a.mailboxes.put(hash, p) { |
| 272 | idRefuse(w) |
| 273 | return |
| 274 | } |
| 275 | if tx.Commit() != nil { |
| 276 | a.mailboxes.remove(hash) |
| 277 | idRefuse(w) |
| 278 | return |
| 279 | } |
| 280 | a.mailboxes.remove(binding) |
| 281 | a.sendRecoverySigninNotice(r.Context(), p.address) |
| 282 | idCookie(w, a.sessions.CookieName(), token, 30*24*3600) |
| 283 | idCookie(w, gateCookie, "", -1) |
| 284 | idCookie(w, recoveryCookie, proof, int(exp.Unix()-now)) |
| 285 | if to == "/" { |
| 286 | to = "/passkey/replace" |
| 287 | } |
| 288 | http.Redirect(w, r, to, http.StatusSeeOther) |
| 289 | } |
| 290 | func (a *App) replacementBinding(tx *sql.Tx, r *http.Request, now int64) (string, string, error) { |
| 291 | s, session, err := a.idSession(tx, r, now) |
| 292 | if err != nil || !strings.HasSuffix(s.Method, "+recovery") { |
| 293 | return "", "", errIDProof |
| 294 | } |
| 295 | proof := cookieValue(r, recoveryCookie) |
| 296 | if proof == "" { |
| 297 | return "", "", errIDProof |
| 298 | } |
| 299 | hash := sessions.HashToken(proof) |
| 300 | var subject string |
| 301 | if err = tx.QueryRow("SELECT subject FROM home_id_recovery_proofs WHERE token_hash=? AND session_hash=? AND subject=? AND expires_at>?", hash, session, s.Subject, now).Scan(&subject); err != nil { |
| 302 | return "", "", errIDProof |
| 303 | } |
| 304 | p, ok := a.mailboxes.get(hash) |
| 305 | if !ok || p.subject != subject { |
| 306 | return "", "", errIDProof |
| 307 | } |
| 308 | return subject, hash, nil |
| 309 | } |
| 310 | func (a *App) handleReplacement(w http.ResponseWriter, r *http.Request) { |
| 311 | tx, now, err := a.idTransaction(r.Context()) |
| 312 | if err != nil { |
| 313 | a.signinFailed(w, r) |
| 314 | return |
| 315 | } |
| 316 | defer tx.Rollback() |
| 317 | subject, _, err := a.replacementBinding(tx, r, now) |
| 318 | if err != nil { |
| 319 | a.signinFailed(w, r) |
| 320 | return |
| 321 | } |
| 322 | if tx.Commit() != nil { |
| 323 | a.signinFailed(w, r) |
| 324 | return |
| 325 | } |
| 326 | a.render(w, r, 200, "id_replace.html", a.passkeyPageData(subject, nil)) |
| 327 | } |
| 328 | func (a *App) replaceCredential(tx *sql.Tx, r *http.Request, subject string, cred webauthn.Credential, now int64) error { |
| 329 | // Removing the old credentials first cannot transfer another person's key: |
| 330 | // the insert below is unique and every deletion rolls back if it fails. |
| 331 | for _, q := range []string{ |
| 332 | "DELETE FROM home_id_discoverable WHERE credential_id IN (SELECT id FROM passkey_credentials WHERE subject=?)", |
| 333 | "DELETE FROM passkey_credentials WHERE subject=?", |
| 334 | "DELETE FROM sessions WHERE subject=?", |
| 335 | "DELETE FROM passkey_recovery_codes WHERE subject=?", |
| 336 | "DELETE FROM passkey_pending WHERE subject=?", |
| 337 | "DELETE FROM passkey_challenges WHERE subject=?", |
| 338 | "DELETE FROM home_id_ceremonies WHERE subject=?", |
| 339 | "DELETE FROM home_id_recovery_proofs WHERE subject=?", |
| 340 | } { |
| 341 | if _, err := tx.Exec(q, subject); err != nil { |
| 342 | return errIDProof |
| 343 | } |
| 344 | } |
| 345 | // Replacement by recovery code is full account control, and it is also |
| 346 | // how a lost device is cut off: every native grant ends (§3). |
| 347 | if err := endGrants(tx, subject, "replacement", now); err != nil { |
| 348 | return err |
| 349 | } |
| 350 | id := hex.EncodeToString(cred.ID) |
| 351 | if _, err := tx.Exec("INSERT INTO passkey_credentials(id,subject,public_key,sign_count,created_at) VALUES(?,?,?,?,?)", id, subject, cred.PublicKey, cred.SignCount, time.Unix(now, 0).UTC().Format(time.RFC3339)); err != nil { |
| 352 | return errIDProof |
| 353 | } |
| 354 | if _, err := tx.Exec("INSERT INTO home_id_discoverable VALUES(?)", id); err != nil { |
| 355 | return errIDProof |
| 356 | } |
| 357 | return nil |
| 358 | } |
| 359 | |
| 360 | const replacementNoticeSubject = "Your Oficina passkeys were replaced" |
| 361 | const replacementNoticeBody = "A replacement passkey was added to your Oficina account. All previous passkeys were removed, all Oficina ID sessions were signed out, and all recovery codes were invalidated. You may remain signed in to the directory and other apps. Sign in with your new passkey to create new recovery codes." |
| 362 | |
| 363 | func (a *App) sendReplacementNotice(ctx context.Context, key string) bool { |
| 364 | p, ok := a.mailboxes.get(key) |
| 365 | if !ok { |
| 366 | return false |
| 367 | } |
| 368 | ctx, cancel := context.WithTimeout(ctx, 5*time.Second) |
| 369 | defer cancel() |
| 370 | if a.secrets.Mailer.Send(ctx, p.address, replacementNoticeSubject, replacementNoticeBody) != nil { |
| 371 | a.logger.Warn("replacement notice delivery failed") |
| 372 | return false |
| 373 | } |
| 374 | a.mailboxes.remove(key) |
| 375 | return true |
| 376 | } |
| 377 | |
| 378 | const replacementResultCookie = "__Host-oficina-replaced" |
| 379 | |
| 380 | type replacementResult struct { |
| 381 | Expires int64 `json:"expires"` |
| 382 | Failed bool `json:"failed"` |
| 383 | } |
| 384 | |
| 385 | func (a *App) replacementResult(w http.ResponseWriter, failed bool) { |
| 386 | b, _ := json.Marshal(replacementResult{time.Now().Unix() + 600, failed}) |
| 387 | sealed, err := a.secrets.Sealer.Seal("id.replaced", b) |
| 388 | if err != nil { |
| 389 | return |
| 390 | } |
| 391 | idCookie(w, replacementResultCookie, base64.RawURLEncoding.EncodeToString(sealed), 600) |
| 392 | } |
| 393 | func (a *App) readReplacementResult(r *http.Request) (replacementResult, bool) { |
| 394 | var out replacementResult |
| 395 | b, err := base64.RawURLEncoding.Strict().DecodeString(cookieValue(r, replacementResultCookie)) |
| 396 | if err != nil { |
| 397 | return out, false |
| 398 | } |
| 399 | b, err = a.secrets.Sealer.Open("id.replaced", b) |
| 400 | if err != nil || json.Unmarshal(b, &out) != nil { |
| 401 | return out, false |
| 402 | } |
| 403 | return out, out.Expires > time.Now().Unix() && out.Expires <= time.Now().Unix()+600 |
| 404 | } |
| 405 | func (a *App) handleReplacementDone(w http.ResponseWriter, r *http.Request) { |
| 406 | result, ok := a.readReplacementResult(r) |
| 407 | if !ok { |
| 408 | a.signinFailed(w, r) |
| 409 | return |
| 410 | } |
| 411 | key := sessions.HashToken(cookieValue(r, noticeCookie)) |
| 412 | _, available := a.mailboxes.get(key) |
| 413 | a.render(w, r, 200, "id_replaced.html", map[string]any{"NoticeFailed": result.Failed, "CanRetry": available}) |
| 414 | } |
| 415 | func (a *App) handleNoticeRetry(w http.ResponseWriter, r *http.Request) { |
| 416 | if result, ok := a.readReplacementResult(r); ok && result.Failed { |
| 417 | success := a.sendReplacementNotice(r.Context(), sessions.HashToken(cookieValue(r, noticeCookie))) |
| 418 | a.replacementResult(w, !success) |
| 419 | } |
| 420 | http.Redirect(w, r, "/passkey/replaced", http.StatusSeeOther) |
| 421 | } |
| 422 | |
| 423 | const recoverySigninNoticeSubject = "A recovery code was used for your Oficina account" |
| 424 | const recoverySigninNoticeBody = "Someone signed in to your Oficina account using email and a recovery code. If this was not you, sign in with your passkey and generate new recovery codes. This invalidates the previous codes but does not sign out anyone already signed in." |
| 425 | |
| 426 | func (a *App) sendRecoverySigninNotice(ctx context.Context, address string) { |
| 427 | ctx, cancel := context.WithTimeout(ctx, 5*time.Second) |
| 428 | defer cancel() |
| 429 | if a.secrets.Mailer.Send(ctx, address, recoverySigninNoticeSubject, recoverySigninNoticeBody) != nil { |
| 430 | a.logger.Error("recovery signin notice failed") |
| 431 | } |
| 432 | } |
| 433 | |