[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

[FD] Follow-Up: Incomplete Remediation of CVE-2020-8166 and CSRF Isolation Weaknesses in Ruby on Rails



Description
On 26 April 2025, we published "Ruby on Rails Cross-Site Request Forgery" 
(https://seclists.org/fulldisclosure/2025/Apr/29), which examined 
`ActionController::RequestForgeryProtection`, but much of the discussion 
surrounding our work fixated on a single question that did not address our 
central argument -- whether prepending a 32-byte random mask (`one_time_pad`) 
to a 32-byte payload produced using exclusive OR (XOR) (`encrypted_csrf_token`) 
is acceptable when its claimed purpose is mitigating "SSL attacks like BREACH". 
 This completely missed the point and the key architectural issues that were 
raised in the write-up, so we are, again, publishing material on the matter but 
doing so more tightly to better confine the discussion and prevent the 
deflections that previously occurred.

In short, when Rails patched CVE-2020-8166 in May 2020, it stopped newly 
generated global tokens from exposing `real_csrf_token`, but the remediation 
remained incomplete with respect to exclusive per-form validation -- it left 
legacy `real_csrf_token` validation active and allowed `global_csrf_token` to 
bypass `per_form_csrf_tokens` isolation in information systems via 
`compare_with_global_token`.  Our write-up discussed token recovery, replay, 
and forgery, but this did not translate into the intended discussions, with 
both acceptance paths still being present in Rails 8.1.4.1, more than a year 
after our previous write-up.

CVE-2020-8166
Prior to Rails 6.0.3.1 and 5.2.4.3, the unscoped branch of 
`masked_authenticity_token` selected the raw 32-byte `real_csrf_token(session)` 
for the `<meta name="csrf-token">` tag, wrapped only in the cleartext-prepended 
XOR mask and Base64-encoded:

```ruby
        raw_token = if per_form_csrf_tokens && action && method
          action_path = normalize_action_path(action)
          per_form_csrf_token(session, action_path, method)
        else
          real_csrf_token(session)
        end

        one_time_pad = SecureRandom.random_bytes(AUTHENTICITY_TOKEN_LENGTH)
        encrypted_csrf_token = xor_byte_strings(one_time_pad, raw_token)
        masked_token = one_time_pad + encrypted_csrf_token
        Base64.strict_encode64(masked_token)
```
_Code snippet from 
`https://github.com/rails/rails/blob/v6.0.3/actionpack/lib/action_controller/metal/request_forgery_protection.rb`,
 lines 321-331_

Importantly, `real_csrf_token(session)` is also the HMAC signing key used to 
generate path- and method-bound tokens, so anyone who obtained a masked 
meta-tag token could simply Base64-decode the token and XOR out the prepended 
`one_time_pad`, recover `real_csrf_token`, and forge valid per-form HMAC tokens 
for every action using the same underlying CSRF secret.  Rails addressed this 
by changing the unscoped branch of `masked_authenticity_token` to mask an 
HMAC-SHA-256 value calculated over a fixed global identifier using 
`real_csrf_token` as the key, instead, making it so that the actual HMAC 
signing key was no longer bled via the meta tag.

The Problem
Rails 8.1.4.1 retains the legacy `real_csrf_token` acceptance and does not 
restrict `global_csrf_token` from overriding `per_form_csrf_tokens`.  When an 
attacker captures a victim's masked token -- however they do it (e.g., from a 
`Referer` containing a token-bearing URL, browser cache, web cache, proxy or 
server logs, DOM or CORS leak) -- they can simply Base64-decode the token and 
XOR the first 32 bytes against the second, immediately exposing the 
`raw_token`, as we previously explained.  Depending on which token tier was 
captured, there exist two key issues: continued exploitation of legacy key 
exposure or bypass of path- and method-bound token validation via 
`global_csrf_token`.  These behaviours concern the authenticity-token check -- 
a successful attack still requires the relevant session context and must 
satisfy any applicable `Origin`, cookie, and authorisation controls.

```ruby
      # Checks the client's masked token to see if it matches the session token.
      # Essentially the inverse of `masked_authenticity_token`.
      def valid_authenticity_token?(session, encoded_masked_token) # :doc:
        if !encoded_masked_token.is_a?(String) || encoded_masked_token.empty?
          return false
        end

        begin
          masked_token = decode_csrf_token(encoded_masked_token)
        rescue ArgumentError # encoded_masked_token is invalid Base64
          return false
        end

        # See if it's actually a masked token or not. In order to deploy this 
code, we
        # should be able to handle any unmasked tokens that we've issued 
without error.

        if masked_token.length == AUTHENTICITY_TOKEN_LENGTH
          # This is actually an unmasked token. This is expected if you have 
just upgraded
          # to masked tokens, but should stop happening shortly after 
installing this gem.
          compare_with_real_token masked_token

        elsif masked_token.length == AUTHENTICITY_TOKEN_LENGTH * 2
          csrf_token = unmask_token(masked_token)

          compare_with_global_token(csrf_token) ||
            compare_with_real_token(csrf_token) ||
            valid_per_form_csrf_token?(csrf_token)
        else
          false # Token is malformed.
        end
      end
```
_Snippet from 
`https://github.com/rails/rails/blob/v8.1.4.1/actionpack/lib/action_controller/metal/request_forgery_protection.rb`,
 lines 507-537_

Continued CVE-2020-8166 Exploitation
Whilst Rails views no longer, themselves, expose `real_csrf_token`, both the 
unmasked 32-byte and the XOR-masked 64-byte `real_csrf_token` values are 
accepted after Base64 decoding, so any Rails-based information system, legacy 
engine, or custom helper that insecurely serialises or masks 
`session[:_csrf_token]` -- the encoded secret when session storage is used -- 
allows the key to be recovered and reused, either directly or indirectly.  
Moreover, unmasking a single legacy token exposes `real_csrf_token`, allowing 
attackers to forge arbitrary per-form HMAC tokens or wrap the raw secret in 
fresh, random XOR pads for as long as the underlying CSRF secret remains valid 
(this technique can be especially useful if middleware attempts to enforce CSRF 
token uniqueness solely by rejecting previously seen encoded token strings, 
among other things).

Bypassing Per-Form CSRF Tokens
Developers may enable `config.action_controller.per_form_csrf_tokens` under the 
assumption that doing so ensures that tokens are scoped to a single 
`action_path` and `method` combination, making token theft a lower risk, but 
Rails' continued rendering of masked `global_csrf_token` via `<meta 
name="csrf-token">` -- `csrf_meta_tags` calls `form_authenticity_token` without 
`action` or `method`, triggering the `global_csrf_token` branch -- and then 
evaluating `compare_with_global_token(csrf_token)` before checking 
`valid_per_form_csrf_token?` means that bleeding a single global token from the 
victim's session allows attackers to obtain a secret that satisfies the 
authenticity-token check across state-changing controllers and HTTP methods 
using the same underlying CSRF secret and validation policy, bypassing the 
path- and method-bound token checks.

Recommended Remediation
To make it clear what is being recommended, we put forward the following:

1. Deprecate and remove direct `real_csrf_token` acceptance -- retire both the 
encoded unmasked and masked legacy validation paths. Any temporary 
compatibility mode should be explicit, with a documented migration path for 
applications still issuing those tokens.
2. Allow disabling or otherwise scoping `global_csrf_token` -- provide a strict 
per-form mode that rejects global and legacy real tokens at validation, through 
both the request parameter and header paths. Disabling meta-tag rendering alone 
is insufficient. Applications using Turbo or other JavaScript clients must be 
able to supply appropriately scoped tokens for their requests.
3. Stop exposing and replace compromised CSRF secrets -- audit custom helpers, 
engines, and token storage, and reset affected secrets where legacy or custom 
code has exposed them. Removing `compare_with_real_token` alone cannot prevent 
an attacker who already knows the HMAC key from calculating tokens accepted by 
the remaining validation paths.
4. Eliminate incorrect, misleading nomenclature -- variables such as 
`encrypted_csrf_token` and `one_time_pad` should be more properly named 
`masked_csrf_token` and `xor_mask` to more accurately align with their intended 
purpose and prevent confusion for developers, the userbase, and those reading 
write-ups that properly quote them.  Importantly, although our original 
write-up was very careful, pointing out that this was not proper "encryption", 
even the presence of such improperly named variables derails discussions, as 
they did in 2025.
_______________________________________________
Sent through the Full Disclosure mailing list
https://nmap.org/mailman/listinfo/fulldisclosure
Web Archives & RSS: https://seclists.org/fulldisclosure/