berty icon indicating copy to clipboard operation
berty copied to clipboard

Stateless OAuth 2.0 Auth Code Replay Vulnerability & Permanent Token Validity

Open codeCraft-Ritik opened this issue 2 months ago • 1 comments

Overview

  • Category: Cryptographic & Security Protocol Violation
  • Severity: High
  • Component: bertyauth
  • Location: go/pkg/bertyauth/services_auth.go:104-142, go/pkg/bertyauth/services_auth_server.go:235-265

Technical Analysis & Root Cause

In services_auth.go and services_auth_server.go, Berty implements an OAuth 2.0 PKCE authentication server for authorizing access to services (e.g. push relays, replication servers, directory services).

Two critical security vulnerabilities exist in token issuance and verification:

1. Replay Attacks on Authorization Codes (Violation of RFC 6749 §4.1.2 & §10.5)

In IssueCode:

func (r *AuthTokenIssuer) IssueCode(codeChallenge string, services []string) (string, error) {
	// ... validation ...
	codePayload := &messengertypes.ServicesTokenCode{
		Services:      services,
		CodeChallenge: codeChallenge,
	}

	payload, err := proto.Marshal(codePayload)
	if err != nil {
		return "", err
	}

	return r.encryptSign(payload)
}

Notice that:

  • ServicesTokenCode contains no issuance timestamp (issued_at), no expiration time (expires_at), and no unique code identifier (nonce).
  • The encrypted code is entirely stateless.
  • During exchange in authTokenServerHTTPOAuthToken:
	codeData, err := a.issuer.VerifyCode(r.Form.Get("code"), r.Form.Get("code_verifier"))
	if err != nil {
		a.authTokenServerJSONError(w, "invalid_request", "invalid value for code", a.logger)
		return
	}

	token, err := a.issuer.IssueToken(codeData.Services)

VerifyCode decrypts the payload and checks the PKCE hash. The server maintains no record of used codes and enforces no expiration time. Consequently, an authorization code can be replayed an infinite number of times, indefinitely into the future, to mint fresh bearer access tokens.

2. Indefinite Validity of Bearer Tokens

In IssueToken:

func (r *AuthTokenIssuer) IssueToken(services []string) (string, error) {
	tokenID, err := uuid.NewV4()
	// ...
	tokenPayload := &messengertypes.ServicesTokenCode{
		Services: services,
		TokenId:  tokenID.String(),
	}
	// ...
	return r.encryptSign(payload)
}

VerifyToken only verifies that TokenId != "" and CodeChallenge == "". Neither the token payload nor the verifier tracks any expiration timestamp or revocation status. An access token, once issued, remains valid forever.

Impact Assessment

  • Replay Attacks: If an authorization code and code verifier are intercepted (via browser redirect logs, deep link handlers, mobile OS IPC, or proxy caches), an adversary can exchange the code indefinitely to obtain new access tokens.
  • Standards Non-Compliance: Directly violates RFC 6749 Section 4.1.2 ("The authorization code MUST expire shortly after issuance. The recommended maximum authorization code lifetime is 10 minutes") and RFC 6749 Section 10.5 ("Authorization codes MUST be short lived and single-use").
  • Permanent Access: Compromised access tokens cannot expire and cannot be invalidated without rotating the service's master private key, invalidating all users.

Step-by-Step Reproduction

  1. Request an authorization code via /oauth/authorize with a PKCE challenge.
  2. Exchange the code via /oauth/token with the code_verifier. Receive access_token_1.
  3. Wait 1 hour (or 1 month).
  4. Re-send the exact same HTTP POST to /oauth/token with the exact same code and code_verifier.
  5. Observed Result: HTTP 200 OK with fresh access_token_2. The server accepts the code indefinitely.
  6. Expected Result: HTTP 400 Bad Request (invalid_grant). The authorization code must expire within 10 minutes and must be rejected upon second use.

Proposed Remediation

  1. Extend ServicesTokenCode in messengertypes.proto to include issued_at and expires_at:
message ServicesTokenCode {
  repeated string services = 1;
  string code_challenge = 2;
  string token_id = 3;
  int64 issued_at = 4;
  int64 expires_at = 5;
}
  1. Enforce code expiration and single-use consumption in services_auth.go:
--- a/go/pkg/bertyauth/services_auth.go
+++ b/go/pkg/bertyauth/services_auth.go
@@ -107,6 +107,8 @@ func (r *AuthTokenIssuer) IssueCode(codeChallenge string, services []string) (s
 	if len(codeChallenge) == 0 {
 		return "", errcode.ErrCode_ErrInvalidInput.Wrap(fmt.Errorf("no codeChallenge specified"))
 	}
+	now := time.Now().Unix()
+	expiresAt := now + 600 // 10 minutes TTL per RFC 6749

 	codePayload := &messengertypes.ServicesTokenCode{
 		Services:      services,
 		CodeChallenge: codeChallenge,
+		IssuedAt:      now,
+		ExpiresAt:     expiresAt,
 	}

 	payload, err := proto.Marshal(codePayload)
@@ -165,6 +167,10 @@ func (r *AuthTokenVerifier) VerifyCode(code, codeVerifier string) (*messengertyp
 	if err := proto.Unmarshal(decrypted, codeObj); err != nil {
 		return nil, err
 	}
+
+	if codeObj.ExpiresAt > 0 && time.Now().Unix() > codeObj.ExpiresAt {
+		return nil, errcode.ErrCode_ErrServicesAuthCodeExpired
+	}

 	if AuthSessionCodeChallenge(codeVerifier) != codeObj.CodeChallenge {
 		return nil, errcode.ErrCode_ErrServicesAuthCodeChallenge

codeCraft-Ritik avatar Sep 30 '26 04:09 codeCraft-Ritik

I looked into this and would like to propose a fix before writing it, since it touches the token format.

What I could confirm

  • Authorization codes from IssueCode carry no issue time, and the token server keeps no record of redeemed codes. So a code can be exchanged for new tokens any number of times, at any later date. RFC 6749 §4.1.2 asks for short-lived, single-use codes.
  • Access tokens from IssueToken never expire, and there's no way to revoke a single token. A leaked token stays valid until the server's secret and signing key are rotated, which invalidates every token.

On severity: PKCE limits the code replay. Exchanging a code also needs the code_verifier, which never leaves the client, so someone who only intercepts the redirect can't use it. Token lifetime is the bigger gap.

Proposed change, in two steps

  1. Codes (no client changes): add an issued_at field to ServicesTokenCode. VerifyCode would reject codes with no issue time or older than 10 minutes, the maximum RFC 6749 recommends. AuthTokenServer would keep an in-memory record of redeemed codes, keyed by a hash of the code, until they expire, so each code works once. Codes issued before the upgrade would be rejected, which only affects a login in progress during a deploy. If the token server runs as several instances, single-use would need shared storage; I'd keep it in-memory unless you say otherwise.
  2. Tokens (needs your call). The options I see:
    • a. An optional expires_at, checked only when present, with a token-server setting for the lifetime (off by default). Existing tokens keep working; the app would need to handle PermissionDenied by re-running the login flow.
    • b. A revocation list of token_ids, checked by the services that verify tokens.
    • c. Keep tokens long-lived by design, and document it.

The PR would include the regenerated files from make generate, since this changes messengertypes.proto.

Would you take step 1 as a PR, and which direction do you prefer for tokens?

chris-buckminster avatar Nov 10 '26 00:11 chris-buckminster