Repository navigation
Enforce single use of TOTP codes (RFC 6238) - #117563
Conversation
A successfully used one-time password is now consumed by the server: it keeps the highest accepted time step per secret and rejects codes for time steps at or before it, as required by RFC 6238, Section 5.2. The code is consumed in `IAccessStorage::authenticateImpl` only after the whole authentication succeeds, so a failed attempt (e.g. a wrong password combined with a valid code) cannot burn the code. Issue: ClickHouse/clickhouse-private#71473 Co-Authored-By: Claude Fable 5 <[email protected]>
|
Preview deployment for your docs. Learn more about Mintlify Previews.
|
|
Workflow [PR], commit [0131c01] Summary: ✅
AI ReviewSummaryThis PR moves TOTP consumption to the end of successful authentication and tracks the highest accepted time step in memory, while reworking the docs and integration tests around single-use codes. The direction is reasonable, but I do not think it is ready to merge: replay prevention still disappears across restarts and replicas, PR Metadata
Findings❌ Blockers
💡 Nits
Tests
Final VerdictChanges requested. LLVM Coverage ReportMeasured on commit 0131c01.
Changed lines: Changed C/C++ lines covered: 64/70 (91.43%) · Uncovered code |
| if (!time_step.has_value()) | ||
| return false; | ||
|
|
||
| static AcceptedOneTimePasswordTimeSteps accepted_time_steps; |
There was a problem hiding this comment.
accepted_time_steps is process-local, so the new "single-use" invariant disappears on restart and is never shared across replicas. A code accepted on one node can still be replayed on another node, and the same node will accept it again after a restart if the validity window has not expired yet.
That means this does not actually enforce RFC 6238-style replay prevention across lifecycle/failover boundaries. Please either persist/share the last accepted step, or explicitly reject/narrow the unsupported restart and multi-node cases instead of claiming full single-use semantics.
| /// One-time passwords are checked only for basic credentials, see `checkBasicAuthentication`. | ||
| const auto * basic_credentials = typeid_cast<const BasicCredentials *>(&credentials); | ||
| if (!basic_credentials) | ||
| return true; |
There was a problem hiding this comment.
This new hook is a no-op for every non-BasicCredentials path, but time_based_one_time_password is attached to PLAINTEXT_PASSWORD and DOUBLE_SHA1_PASSWORD methods too. On mysql_port, those users authenticate via MySQLNative41Credentials, checkMySQLAuthentication never looks at otp_secret, and this branch returns true, so TOTP is silently bypassed there.
In other words, a user configured as <password>/<password_double_sha1_hex> plus time_based_one_time_password can still log in over the MySQL protocol with only the password response and can replay it indefinitely. Please either reject that configuration on the mysql_native_password path or make the MySQL protocol refuse those users until it can carry and consume the second factor.
| To authenticate using TOTP, users must provide a primary password along with a one-time password generated by their TOTP application via the `--one-time-password` command line option or concatenated to main password together with a '+' character. | ||
| For example if the primary password is `some_password` and the generated TOTP code is `345123`, user may specify `--password some_password+345123` or `--password some_password --one-time-password 345123` when connecting to ClickHouse. If no password specified `clickhouse-client` will prompt for it interactively. | ||
|
|
||
| Each code is accepted at most once, as required by [RFC 6238](https://datatracker.ietf.org/doc/html/rfc6238#section-5.2), so a user can successfully authenticate at most once per `period`. |
There was a problem hiding this comment.
The first sentence is fine, but the "at most once per period" conclusion is stronger than the implementation. Because the verifier still accepts the next time step early (delta = +1), a user can authenticate twice within one wall-clock period by using the current code and then the next-step code before the boundary.
The contract here is "each accepted code / time step is single-use", not "one successful authentication per period". Please tighten the wording, or tighten the acceptance window if you really want the stronger guarantee.
The flaky check runs each test repeatedly (--count) against the same cluster, and the server now keeps used one-time passwords in memory, so a repeated run saw its codes already consumed and failed with AUTHENTICATION_FAILED. Restart the server before each test to reset that state (requires stay_alive=True). Failed check: https://github.com/ClickHouse/ClickHouse/actions/runs/33543527485/job/100005003155 PR: #117563 Co-Authored-By: Claude Fable 5 <[email protected]>
Build profile diff (arm_release)Comparing ✅ No significant changes. Binary sizes
The official master build is compiled with Compile time of recompiled translation units144 translation units recompiled, 882 s compile time in total, 144 of them have a recent master baseline. |
The flaky and targeted integration checks run the whole module in several pytest workers at once (`--dist=each`). Each worker generated its own random TOTP secrets and rewrote the shared `config/users.xml`, so only the last writer's server matched its secrets, and every successful login of the other workers failed with `AUTHENTICATION_FAILED`. The module passed in the regular shards, which run it in a single worker. Commit the config with fixed secrets of nine different lengths (3 to 64 bytes, covering all base32 padding variants) and read the secrets and TOTP parameters from it in the test. CI: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=117563&sha=246d989e15a543279fa2d093201079095fd5b285&name_0=PR&name_1=Integration%20tests%20(amd_asan_ubsan%2C%20flaky) PR: #117563
| if (one_time_password.empty()) | ||
| return true; | ||
|
|
||
| return checkAndConsumeOneTimePassword(one_time_password, *otp_secret); |
There was a problem hiding this comment.
checkBasicAuthentication has already accepted this TOTP once, but consumeOneTimePassword re-runs checkAndConsumeOneTimePassword against a fresh time(nullptr). A previous-window code that is valid at t = k * period + period - 1 stops matching one second later, so a login can pass the first check and then be rejected here if the period boundary falls between the two calls; the user then gets "already been used" even though the code was never consumed.
To keep the "failed attempts don't burn a code" property without reintroducing boundary flakiness, the first check needs to return (or stash) the matched time step and the consume step should use that exact step instead of revalidating against wall clock again.
| hash.update(secret.params.num_digits); | ||
| hash.update(secret.params.period); | ||
| hash.update(secret.params.algorithm); | ||
| const UInt128 key = hash.get128(); |
There was a problem hiding this comment.
This starts keying runtime state by secret / period, but the live users.xml reload path still treats a TOTP-only change as "no auth change": AuthenticationData::operator== ignores otp_secret (src/Access/AuthenticationData.cpp:153-166), User::equal compares auth methods via that operator (src/Access/User.cpp:19-22), and MemoryAccessStorage::insertNoLock keeps the old entity when the comparison says equal (src/Access/MemoryAccessStorage.cpp:128-139).
So rotating only time_based_one_time_password.secret or period and running SYSTEM RELOAD USERS leaves the old factor active until restart. Please make otp_secret participate in AuthenticationData equality and add a focused reload test for that path.
|
I think we'd need to make use of coordination to be compliant with the RFC. |
This seems much harder and will require some atomic synchronization between server, so it will be under some flag like |
Cherry pick #117563 to 26.3: Enforce single use of TOTP codes (RFC 6238)
Cherry pick #117563 to 26.6: Enforce single use of TOTP codes (RFC 6238)
Cherry pick #117563 to 26.7: Enforce single use of TOTP codes (RFC 6238)
Cherry pick #117563 to 26.8: Enforce single use of TOTP codes (RFC 6238)
Backport #117563 to 26.6: Enforce single use of TOTP codes (RFC 6238)
Backport #117563 to 26.8: Enforce single use of TOTP codes (RFC 6238)
Backport #117563 to 26.3: Enforce single use of TOTP codes (RFC 6238)
Backport #117563 to 26.7: Enforce single use of TOTP codes (RFC 6238)
Each code of a time-based one-time password is accepted at most once per server since #117563, but the used codes were tracked in process memory, so a code could still be replayed once on every other replica and again after a restart. With the new server setting `totp_strict_mode` the accepted codes are tracked in Keeper under `/clickhouse/access/one_time_passwords`: one node per user, named by the SHA-256 hash of the user name, holding the start of the last accepted time step and advanced with compare-and-set. A code accepted by one server is then rejected by all servers sharing that Keeper and after restarts. Keeper must be configured; while it is unavailable, authentication with a one-time password fails. The tracking moves from a static in `OneTimePassword.cpp` into `OneTimePasswordUsageTracker`, owned by `AccessControl`, and the code is now consumed in `AccessControl::authenticate` once the whole authentication succeeded, so the storages stay pure verifiers. The per-server map is kept for the default mode and as a pre-filter in strict mode. The entries are keyed by user and store the start of the time step rather than its number, so a change of `period` cannot lock a user out. Co-Authored-By: Claude Fable 5.1 <[email protected]>
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
time_based_one_time_passwordcan successfully authenticate at most once perperiod.A valid one-time password could previously be replayed for the whole validity window (up to
2 × period):checkOneTimePasswordvalidated the code against the adjacent time steps but never recorded used codes, violating RFC 6238, Section 5.2.Now the server keeps the highest accepted time step per TOTP secret (in memory, keyed by a hash of the secret) and rejects any code for a time step at or before it. The code is consumed in
IAccessStorage::authenticateImplonly after the whole authentication succeeds: the checks in the method-matching loop and in the fail-close grant-narrowing scan stay pure, so a failed attempt (e.g. a wrong password combined with a valid code) cannot burn the code, and probing multiple authentication methods cannot double-consume it.Notes:
int(timepoint or time.time() / interval)) that made alltimepoint-based codes garbage.Workflow [PR]
Sync PR [sync-upstream/pr/117563]
Version info
26.9.1.1206(included in26.9and later)26.8.5.13,26.7.9.14,26.6.7.19,26.3.33.86