Skip to content

Enforce single use of TOTP codes (RFC 6238) - #117563

Merged
vdimir merged 4 commits into
masterfrom
vdimir/totp-single-use
Sep 11, 2026
Merged

vdimir merged 4 commits into
masterfrom
vdimir/totp-single-use

Conversation

@vdimir

@vdimir vdimir commented Sep 1, 2026 •

Copy link
Copy Markdown
Member

Changelog category (leave one):

  • Critical Bug Fix (crash, data loss, RBAC)

Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):

  • Each code for Time-based one-time password is now accepted at most once, as required by RFC 6238: reusing an already used code, or a code for an earlier time step, is rejected. A user with time_based_one_time_password can successfully authenticate at most once per period.

A valid one-time password could previously be replayed for the whole validity window (up to 2 × period): checkOneTimePassword validated 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::authenticateImpl only 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:

  • The used-codes state is local to the server process: it is not shared between replicas and does not survive a restart.
  • Clients that authenticate on every request or connection (e.g. scripts using the HTTP interface) now need a fresh code for each authentication; documentation is updated accordingly.
  • The integration tests are reworked to use dedicated users per test, since a code can no longer be reused within its time window. This also fixes an operator-precedence bug in the test helper (int(timepoint or time.time() / interval)) that made all timepoint-based codes garbage.

Workflow [PR]
Sync PR [sync-upstream/pr/117563]

Version info

  • Merged into: 26.9.1.1206 (included in 26.9 and later)
  • Backported to: 26.8.5.13, 26.7.9.14, 26.6.7.19, 26.3.33.86

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]>
@mintlify

mintlify Bot commented Sep 1, 2026 •

Copy link
Copy Markdown
Contributor

Preview deployment for your docs. Learn more about Mintlify Previews.

Project Status Preview Updated (UTC)
ClickHouse-docs 🟢 Ready View Preview Sep 1, 2026, 6:56 PM

@clickhouse-gh

clickhouse-gh Bot commented Sep 1, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [0131c01]

Summary: ✅


AI Review

Summary

This 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, mysql_port can bypass the second factor, the new consume step can reject a code that just passed validation, and users.xml reloads still ignore TOTP-only rotations.

PR Metadata

Changelog category: acceptable as Critical Bug Fix.

Changelog entry: required and specific, but the sentence about "at most once per period" overstates the current implementation. Suggested replacement:
Prevent replay of previously accepted time-based one-time passwords during password-based authentication, without consuming a code when the rest of the authentication attempt fails.

Findings

❌ Blockers

  • [src/Access/Common/OneTimePassword.cpp:223] Replay prevention is stored only in a process-local static map, so the same TOTP can be replayed after a restart and on any other replica that shares the user configuration. Suggested fix: persist/share the last accepted time step per secret, or explicitly reject/narrow the unsupported restart and multi-node cases instead of claiming RFC 6238 replay prevention.
  • [src/Access/Authentication.cpp:422-437] mysql_port still bypasses TOTP for PLAINTEXT_PASSWORD / DOUBLE_SHA1_PASSWORD users because MySQLNative41Credentials never check otp_secret and consumeOneTimePassword becomes a no-op on non-BasicCredentials. Suggested fix: either make the MySQL protocol carry and consume the second factor, or reject those TOTP configurations on the mysql_native_password path.

⚠️ Majors

  • [src/Access/Common/OneTimePassword.cpp:178-199] Rotating only time_based_one_time_password.secret or period in users.xml does not take effect on SYSTEM RELOAD USERS: AuthenticationData::operator== still ignores otp_secret, User::equal delegates to it, and MemoryAccessStorage::insertNoLock keeps the old entity when equality says "unchanged". Suggested fix: include otp_secret in AuthenticationData equality and add a focused reload test.
  • [src/Access/Authentication.cpp:433-437] The consume step re-validates the TOTP against a fresh time(nullptr) instead of consuming the time step that the first check already accepted. A previous-window code that passes checkBasicAuthentication in the last second before a boundary can therefore fail here one second later and be reported as "already used". Suggested fix: return or stash the matched time step from the initial validation and consume that exact step.

💡 Nits

  • [docs/concepts/features/configuration/settings/settings-users.mdx:127] "at most once per period" is stronger than the current behavior: the next-step code is accepted early, so two successful logins can happen within one wall-clock period. Suggested fix: document single-use per accepted code / time step, or tighten the acceptance window if you want the stronger guarantee.
Tests
  • ⚠️ Add a mysql_port integration test for a TOTP user authenticated through the mysql_native_password / MySQLNative41Credentials path.
  • ⚠️ Add a SYSTEM RELOAD USERS or config-reloader test that rotates only time_based_one_time_password.secret / period and proves the new factor takes effect without restart.
  • ⚠️ Add a boundary-focused test proving that a valid previous-window code cannot pass the first check and then fail in consumeOneTimePassword when the wall clock crosses into the next step.
Final Verdict

Changes requested.

LLVM Coverage Report

Measured on commit 0131c01.

Metric Baseline Current Δ
Lines 88.70% 88.70% +0.00%
Functions 92.10% 92.10% +0.00%
Branches 81.00% 81.00% +0.00%

Changed lines: Changed C/C++ lines covered: 64/70 (91.43%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added pr-critical-bugfix pr-must-backport Pull request should be backported intentionally. Use this label with great care! labels Sep 1, 2026
if (!time_step.has_value())
return false;

static AcceptedOneTimePasswordTimeSteps accepted_time_steps;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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`.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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]>
@clickhouse-gh

clickhouse-gh Bot commented Sep 1, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 0131c0150 with master a748a4544 (stripped binary size, per-symbol sizes and ThinLTO time; compile times per translation unit against the most recent warmup build that recompiled it).

✅ No significant changes.

Binary sizes

programs/clickhouse-stripped: smaller than the master baseline by the known offset between the two builds, so the difference is not shown. A delta that differs from the offset by more than 50% of it is shown, in either direction.

The official master build is compiled with -g and a pull request build is not, and XRay counts debug instructions towards its instrumentation threshold, so master instruments thousands of functions more and its binary is ~0.4% larger no matter what the pull request does.

Compile time of recompiled translation units

144 translation units recompiled, 882 s compile time in total, 144 of them have a recent master baseline.

Job report

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);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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();

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

@clickhouse-gh clickhouse-gh Bot added the comp-authentication Identity verification: users, credentials, auth methods, external auth providers. label Sep 4, 2026
@thevar1able

thevar1able commented Sep 7, 2026 •

Copy link
Copy Markdown
Member

I think we'd need to make use of coordination to be compliant with the RFC.

@thevar1able thevar1able self-assigned this Sep 7, 2026
@vdimir

vdimir commented Sep 10, 2026

Copy link
Copy Markdown
Member Author

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 totp_enable_strict_reuse_policy since it introduces much overhead and makes it unable to log in on a partially available cluster. Perhaps we can go with a per-server local fix first, and consider a fix for the distributed case later.

@vdimir
vdimir added this pull request to the merge queue Sep 11, 2026
Merged via the queue into master with commit 9f14862 Sep 11, 2026
175 checks passed
@vdimir
vdimir deleted the vdimir/totp-single-use branch September 11, 2026 15:07
@robot-clickhouse-ci-1 robot-clickhouse-ci-1 added the pr-synced-to-cloud The PR is synced to the cloud repo label Sep 11, 2026
@robot-clickhouse robot-clickhouse added the pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR label Sep 11, 2026
robot-clickhouse-ci-2 added a commit that referenced this pull request Sep 15, 2026
Cherry pick #117563 to 26.3: Enforce single use of TOTP codes (RFC 6238)
robot-clickhouse-ci-2 added a commit that referenced this pull request Sep 15, 2026
Cherry pick #117563 to 26.6: Enforce single use of TOTP codes (RFC 6238)
PedroTadim added a commit that referenced this pull request Sep 15, 2026
Cherry pick #117563 to 26.7: Enforce single use of TOTP codes (RFC 6238)
PedroTadim added a commit that referenced this pull request Sep 15, 2026
Cherry pick #117563 to 26.8: Enforce single use of TOTP codes (RFC 6238)
@robot-ch-test-poll2 robot-ch-test-poll2 added the pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore label Sep 15, 2026
clickhouse-gh Bot added a commit that referenced this pull request Sep 15, 2026
Backport #117563 to 26.6: Enforce single use of TOTP codes (RFC 6238)
clickhouse-gh Bot added a commit that referenced this pull request Sep 15, 2026
Backport #117563 to 26.8: Enforce single use of TOTP codes (RFC 6238)
PedroTadim added a commit that referenced this pull request Sep 15, 2026
Backport #117563 to 26.3: Enforce single use of TOTP codes (RFC 6238)
clickhouse-gh Bot added a commit that referenced this pull request Sep 15, 2026
Backport #117563 to 26.7: Enforce single use of TOTP codes (RFC 6238)
vdimir added a commit that referenced this pull request Oct 14, 2026
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]>

This branch was successfully deployed

1 active deployment
staging - docs — 0131c015 Deployed Sep 3, 2026 by mintlify[bot]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

comp-authentication Identity verification: users, credentials, auth methods, external auth providers. pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore pr-critical-bugfix pr-must-backport Pull request should be backported intentionally. Use this label with great care! pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR pr-synced-to-cloud The PR is synced to the cloud repo

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants