[GH-ISSUE #6535] [Bug]: 2FA login fails with "invalid 2FA code" and then succeeds on an immediate retry #4384

Closed
opened 2026-10-31 20:39:18 +07:00 by bsakaguchi · 1 comment
Owner

Originally created by @JinerJia on GitHub (Sep 15, 2026).
Original GitHub issue: https://github.com/MHSanaei/3x-ui/issues/6535

Describe the bug

Every time I log in with two-factor authentication (2FA), an error occurs.
Logs:
2026/09/15 00:55:01 INFO - X-UI: logged in successfully: username="KBupor36pq", IP="60.209.181.226"
2026/09/15 00:54:59 WARNING - X-UI: failed login: username="KBupor36pq", IP="60.209.181.226", reason="invalid 2FA code"

How to reproduce the problem

1.Pannel Settings--Authentication--Two-factor authentication
2.Enable 2FA
3.Login

Expected behavior

No response

Actual behavior

No response

Relevant logs


Screenshots

No response

3x-ui version

3.8.0

Xray-core version

No response

How did you install 3x-ui?

install.sh script

Operating system

Debian 13

Which parts of the panel are affected?

No response

Browser (only if it is a UI bug)

No response

Is the panel behind a reverse proxy or CDN?

No response

Before submitting

  • I searched existing issues and this bug has not been reported.
  • I am running the latest released version of 3x-ui (or have verified the bug still exists on it).
  • This bug report is written in English.
  • I have redacted any sensitive data (tokens, real domains, client UUIDs).
Originally created by @JinerJia on GitHub (Sep 15, 2026). Original GitHub issue: https://github.com/MHSanaei/3x-ui/issues/6535 ### Describe the bug Every time I log in with two-factor authentication (2FA), an error occurs. Logs: 2026/09/15 00:55:01 INFO - X-UI: logged in successfully: username="KBupor36pq", IP="60.209.181.226" 2026/09/15 00:54:59 WARNING - X-UI: failed login: username="KBupor36pq", IP="60.209.181.226", reason="invalid 2FA code" ### How to reproduce the problem 1.Pannel Settings--Authentication--Two-factor authentication 2.Enable 2FA 3.Login ### Expected behavior _No response_ ### Actual behavior _No response_ ### Relevant logs ```shell ``` ### Screenshots _No response_ ### 3x-ui version 3.8.0 ### Xray-core version _No response_ ### How did you install 3x-ui? install.sh script ### Operating system Debian 13 ### Which parts of the panel are affected? _No response_ ### Browser (only if it is a UI bug) _No response_ ### Is the panel behind a reverse proxy or CDN? _No response_ ### Before submitting - [x] I searched [existing issues](../issues?q=is%3Aissue) and this bug has not been reported. - [x] I am running the latest released version of 3x-ui (or have verified the bug still exists on it). - [x] This bug report is written in English. - [x] I have redacted any sensitive data (tokens, real domains, client UUIDs).
bsakaguchi 2026-10-31 20:39:18 +07:00
  • closed this issue
  • added the
    bug
    label
Author
Owner

@github-actions[bot] commented on GitHub (Sep 15, 2026):

Confirmed bug: the panel accepts only the TOTP code for the exact 30-second step the server is in at the moment the request is evaluated — there is no tolerance for the previous/next step, so a code that was valid on your phone a second or two earlier is rejected. Your two log lines straddle a step boundary (00:54:59 failed, 00:55:01 succeeded — the boundary is 00:55:00), which is the signature of exactly that.

What the code does

The login check is a plain equality against a single generated value, internal/web/service/panel/user.go:100:

if gotp.NewDefaultTOTP(twoFactorToken).Now() != twoFactorCode {
    return nil, errors.New("invalid 2fa code")
}

.Now() produces the code for the current instant only. There is no ±1 time-step window, which RFC 6238 §5.2 recommends and which virtually every TOTP verifier implements. The period really is 30 s: the QR/URI the panel hands your authenticator app is built with period: 30, digits: 6 (frontend/src/pages/settings/TwoFactorModal.tsx:41-45).

Two things follow from your log that are worth stating plainly:

  1. Your username and password were correct. The 2FA comparison is only reached after the password (or LDAP) check passes — internal/web/service/panel/user.go:54-93 — and the log reason is produced solely by that comparison (internal/web/controller/index.go:132-137). So the only thing that failed was the code.
  2. The login page shows the same generic "wrong username or password" toast for a bad password and a bad code (internal/web/controller/index.go:111), which is why the failure looks like a credentials error in the UI.

A second, smaller asymmetry in the same area: the setup-time check trims whitespace, internal/web/service/setting.go:658:

if strings.TrimSpace(token) == "" || !gotp.NewDefaultTOTP(token).Verify(strings.TrimSpace(code), time.Now().Unix()) {

…but the login-time check at user.go:100 compares the raw submitted string, and the login form only requires a non-empty value (TwoFactorCodeSchema = z.string().min(1, ...), frontend/src/schemas/login.ts:9). A pasted or autofilled code carrying a leading/trailing space is therefore rejected at login while the identical input would be accepted in the settings dialog.

What you can do right now

  1. Check the server's clock against your phone. A server running a few seconds behind your authenticator makes this fail on essentially every login, because people normally type the code right after it refreshes:
timedatectl status
sudo timedatectl set-ntp true
  1. Enter the code in the first half of its 30-second life, not the last seconds.
  2. Watch the lockout: 5 failed logins from the same IP/username within 5 minutes block that combination for 15 minutes (loginLimitMaxFailures = 5, loginLimitWindow = 5 * time.Minute, loginLimitCooldown = 15 * time.Minute, internal/web/controller/login_limiter.go:9-17). Repeatedly retrying a stale code can lock you out.
  3. If you get locked out of the panel, 2FA can be turned off from the server:
x-ui setting -resetTwoFactor

(also available as the x-ui menu's Reset Username & Password step; see First login → Two-factor authentication).


Verdict: Confirmed bug
Severity: Medium
Confidence: Medium
Root cause: internal/web/service/panel/user.go:100, UserService.CheckUser — gotp.NewDefaultTOTP(twoFactorToken).Now() != twoFactorCode accepts only the current 30-second step, with no ±1-step skew tolerance and no TrimSpace on the submitted code. Triggered whenever the step rolls over between the authenticator generating the code and the server evaluating it, or whenever the server clock is offset from the client's by a few seconds. Introduced in fe3b1c9b "chore: implement 2fa auth (#2968)" (the line is unchanged since, only relocated by 41645255).
Already fixed: Still present on the default branch (a810f497); git log -S "NewDefaultTOTP" -- internal/ shows only the introducing commit and the internal/ relocation.
Duplicate of: None. Related: #3880 (login API returns the same response for a wrong password and a wrong 2FA code — same generic-message behaviour, different root cause).
Evidence: internal/web/service/panel/user.go:100 — if gotp.NewDefaultTOTP(twoFactorToken).Now() != twoFactorCode {; internal/web/controller/index.go:133 — if err != nil && err.Error() == "invalid 2fa code" (the reason string in the reporter's log comes only from this path, i.e. the password already verified); internal/web/service/setting.go:658 — the setup path trims and the login path does not; frontend/src/pages/settings/TwoFactorModal.tsx:41-45 — period: 30, digits: 6; internal/web/controller/login_limiter.go:9-17 — 5 failures / 5 min / 15 min lockout. No test asserts that an adjacent step must be rejected: TestVerifyTwoFactorCode (internal/web/service/setting_security_test.go:219-236) only checks a code generated at the same instant plus the literal "000000", so the no-window behaviour is not pinned as intended anywhere.
Not determined: The actual offset between this server's clock and the reporter's authenticator — timedatectl status on the server, compared against the phone, would show whether this is routine step-rollover or a standing clock skew. I could not reproduce or run anything here; all statements above come from reading the source at the tip.

Suggested fix: Verify the submitted code against the adjacent time steps as well as the current one, instead of a single .Now() equality, and trim the submitted code the way SettingService.VerifyTwoFactorCode already does. A regression test that generates a code one step in the past and asserts the login still accepts it would fail today.

This reply was generated automatically; a maintainer may follow up.

<!-- gh-comment-id:5673166144 --> @github-actions[bot] commented on GitHub (Sep 15, 2026): Confirmed bug: the panel accepts **only** the TOTP code for the exact 30-second step the server is in at the moment the request is evaluated — there is no tolerance for the previous/next step, so a code that was valid on your phone a second or two earlier is rejected. Your two log lines straddle a step boundary (`00:54:59` failed, `00:55:01` succeeded — the boundary is `00:55:00`), which is the signature of exactly that. ## What the code does The login check is a plain equality against a single generated value, `internal/web/service/panel/user.go:100`: ```go if gotp.NewDefaultTOTP(twoFactorToken).Now() != twoFactorCode { return nil, errors.New("invalid 2fa code") } ``` `.Now()` produces the code for the current instant only. There is no ±1 time-step window, which RFC 6238 §5.2 recommends and which virtually every TOTP verifier implements. The period really is 30 s: the QR/URI the panel hands your authenticator app is built with `period: 30, digits: 6` (`frontend/src/pages/settings/TwoFactorModal.tsx:41-45`). Two things follow from your log that are worth stating plainly: 1. Your username and password were **correct**. The 2FA comparison is only reached after the password (or LDAP) check passes — `internal/web/service/panel/user.go:54-93` — and the log reason is produced solely by that comparison (`internal/web/controller/index.go:132-137`). So the only thing that failed was the code. 2. The login page shows the same generic "wrong username or password" toast for a bad password and a bad code (`internal/web/controller/index.go:111`), which is why the failure looks like a credentials error in the UI. A second, smaller asymmetry in the same area: the setup-time check trims whitespace, `internal/web/service/setting.go:658`: ```go if strings.TrimSpace(token) == "" || !gotp.NewDefaultTOTP(token).Verify(strings.TrimSpace(code), time.Now().Unix()) { ``` …but the login-time check at `user.go:100` compares the raw submitted string, and the login form only requires a non-empty value (`TwoFactorCodeSchema = z.string().min(1, ...)`, `frontend/src/schemas/login.ts:9`). A pasted or autofilled code carrying a leading/trailing space is therefore rejected at login while the identical input would be accepted in the settings dialog. ## What you can do right now 1. Check the server's clock against your phone. A server running a few seconds behind your authenticator makes this fail on essentially every login, because people normally type the code right after it refreshes: ```bash timedatectl status sudo timedatectl set-ntp true ``` 2. Enter the code in the first half of its 30-second life, not the last seconds. 3. Watch the lockout: **5** failed logins from the same IP/username within **5 minutes** block that combination for **15 minutes** (`loginLimitMaxFailures = 5`, `loginLimitWindow = 5 * time.Minute`, `loginLimitCooldown = 15 * time.Minute`, `internal/web/controller/login_limiter.go:9-17`). Repeatedly retrying a stale code can lock you out. 4. If you get locked out of the panel, 2FA can be turned off from the server: ```bash x-ui setting -resetTwoFactor ``` (also available as the `x-ui` menu's **Reset Username & Password** step; see [First login → Two-factor authentication](https://github.com/MHSanaei/3x-ui/blob/main/docs/content/docs/en/guide/first-login.mdx)). --- Verdict: Confirmed bug Severity: Medium Confidence: Medium Root cause: `internal/web/service/panel/user.go:100`, `UserService.CheckUser` — `gotp.NewDefaultTOTP(twoFactorToken).Now() != twoFactorCode` accepts only the current 30-second step, with no ±1-step skew tolerance and no `TrimSpace` on the submitted code. Triggered whenever the step rolls over between the authenticator generating the code and the server evaluating it, or whenever the server clock is offset from the client's by a few seconds. Introduced in `fe3b1c9b` "chore: implement 2fa auth (#2968)" (the line is unchanged since, only relocated by `41645255`). Already fixed: Still present on the default branch (`a810f497`); `git log -S "NewDefaultTOTP" -- internal/` shows only the introducing commit and the `internal/` relocation. Duplicate of: None. Related: #3880 (login API returns the same response for a wrong password and a wrong 2FA code — same generic-message behaviour, different root cause). Evidence: `internal/web/service/panel/user.go:100` — `if gotp.NewDefaultTOTP(twoFactorToken).Now() != twoFactorCode {`; `internal/web/controller/index.go:133` — `if err != nil && err.Error() == "invalid 2fa code"` (the reason string in the reporter's log comes only from this path, i.e. the password already verified); `internal/web/service/setting.go:658` — the setup path trims and the login path does not; `frontend/src/pages/settings/TwoFactorModal.tsx:41-45` — `period: 30, digits: 6`; `internal/web/controller/login_limiter.go:9-17` — 5 failures / 5 min / 15 min lockout. No test asserts that an adjacent step must be rejected: `TestVerifyTwoFactorCode` (`internal/web/service/setting_security_test.go:219-236`) only checks a code generated at the same instant plus the literal `"000000"`, so the no-window behaviour is not pinned as intended anywhere. Not determined: The actual offset between this server's clock and the reporter's authenticator — `timedatectl status` on the server, compared against the phone, would show whether this is routine step-rollover or a standing clock skew. I could not reproduce or run anything here; all statements above come from reading the source at the tip. Suggested fix: Verify the submitted code against the adjacent time steps as well as the current one, instead of a single `.Now()` equality, and trim the submitted code the way `SettingService.VerifyTwoFactorCode` already does. A regression test that generates a code one step in the past and asserts the login still accepts it would fail today. *This reply was generated automatically; a maintainer may follow up.* <!-- claude-issue:analyst -->
Sign in to join this conversation.
No milestone
No project
No assignees
1 participant
Notifications
Due date
The due date is invalid or out of range. Please use the format "yyyy-mm-dd".

No due date set.

Dependencies

No dependencies set.

Reference
MHSanaei/3x-ui#4384
No description provided.