CVE-2023-40021 (published 2023-08-16T21:15Z)

Oppia is an online learning platform. When comparing a received CSRF token against the expected token, Oppia uses the string equality operator (`==`), which is not safe against timing attacks. By repeatedly submitting invalid tokens, an attacker can brute-force the expected CSRF token character by character. Once they have recovered the token, they can then submit a forged request on behalf of a logged-in user and execute privileged actions on that user's behalf. In particular the function to validate received CSRF tokens is at `oppia.core.controllers.base.CsrfTokenManager.is_csrf_token_valid`. An attacker who can lure a logged-in Oppia user to a malicious website can perform any change on Oppia that the user is authorized to do, including changing profile information; creating, deleting, and changing explorations; etc. Note that the attacker cannot change a user's login credentials. An attack would need to complete within 1 second because every second, the time used in computing the token changes. This issue has been addressed in commit `b89bf80837` which has been included in release `3.3.2-hotfix-2`. Users are advised to upgrade. There are no known workarounds for this vulnerability.

CVSS v3 base score: 5.3, MEDIUM (CVSS:3.1/AV:N/AC:H/PR:N/UI:R/S:U/C:N/I:H/A:N)

Weakness information:
cwe_id: CWE-203
cwe_name: Observable Discrepancy
description: The product behaves differently or sends different responses under different circumstances in a way that is observable to an unauthorized actor, which exposes security-relevant information about the state of the product, such as whether a particular operation was successful or not.
extended_description: Discrepancies can take many forms, and variations may be detectable in timing, control flow, communications such as replies or requests, or general behavior. These discrepancies can reveal information about the product's operation or internal state to an unauthorized actor. In some cases, discrepancies can be used by attackers to form a side channel.
         

Fix information:
repo_url: https://github.com/oppia/oppia
commit_details: repo_url: https://github.com/oppia/oppia
author: U8N WXD
author_date: 2023-08-12 21:18:25-04:00
msg: Fix GHSA-49jp-pjc3-2532: Strengthen CSRF Protections (#18769)

* Strengthen CSRF Protections

Adds the following protections:
* A nonce to prevent collisions. This is best practice per OWASP.
* A constant-time comparison of expected and received tokens.
* HMAC-SHA256 instead of HMAC-MD5. Even though HMAC-MD5 is not broken
  yet, attacks against MD5 have been getting better, and there's no
  reason not to switch to SHA256.

* Fix base controller tests
repository: repo_url: https://github.com/oppia/oppia
repo_name: oppia/oppia
description: A free, online learning platform to make quality education accessible for all.
repo_language: Python
owner: oppia
file_changes: filename: base.py
change_type: ModificationType.MODIFY
diff: @@ -902,12 +902,18 @@ class CsrfTokenManager:
             base64.urlsafe_b64encode(os.urandom(20)))
 
     @classmethod
-    def _create_token(cls, user_id: Optional[str], issued_on: float) -> str:
+    def _create_token(
+            cls, user_id: Optional[str], issued_on: float,
+            nonce: Optional[str] = None) -> str:
         """Creates a new CSRF token.
 
         Args:
             user_id: str|None. The user_id for which the token is generated.
             issued_on: float. The timestamp at which the token was issued.
+            nonce: str|None. A token that is never reused to prevent reply
+                attacks. This argument should only be provided when validating a
+                received CSRF token, in which case the nonce in the received
+                token should be provided here.
 
         Returns:
             str. The generated CSRF token.
@@ -923,19 +929,31 @@ class CsrfTokenManager:
         # Round time to seconds.
         issued_on_str = str(int(issued_on))
 
+        # Generate a nonce (number used once) to ensure that even two
+        # consecutive calls to the same endpoint in the same second generate
+        # different tokens. Note that this nonce is just for anti-collision
+        # purposes, so it's okay that the nonce is stored in the CSRF token and
+        # therefore can be controlled by an attacker. See OWASP guidance here:
+        # https://cheatsheetseries.owasp.org/cheatsheets/Cross-Site_Request_Forgery_Prevention_Cheat_Sheet.html#signed-double-submit-cookie.
+        if nonce is None:
+            nonce = base64.urlsafe_b64encode(os.urandom(20)).decode('utf-8')
+
         digester = hmac.new(
             key=CSRF_SECRET.value.encode('utf-8'),
-            digestmod='md5'
+            digestmod='sha256'
         )
         digester.update(user_id.encode('utf-8'))
         digester.update(b':')
         digester.update(issued_on_str.encode('utf-8'))
+        digester.update(b':')
+        digester.update(nonce.encode('utf-8'))
 
         digest = digester.digest()
         # The b64encode returns bytes, so we first need to decode the returned
         # bytes to string.
-        token = '%s/%s' % (
-            issued_on_str, base64.urlsafe_b64encode(digest).decode('utf-8'))
+        token = '%s/%s/%s' % (
+            issued_on_str, nonce,
+            base64.urlsafe_b64encode(digest).decode('utf-8'))
 
         return token
 
@@ -973,7 +991,7 @@ class CsrfTokenManager:
         """
         try:
             parts = token.split('/')
-            if len(parts) != 2:
+            if len(parts) != 3:
                 return False
 
             issued_on = int(parts[0])
@@ -981,8 +999,12 @@ class CsrfTokenManager:
             if age > cls._CSRF_TOKEN_AGE_SECS:
                 return False
 
-            authentic_token = cls._create_token(user_id, issued_on)
-            if authentic_token == token:
+            nonce = parts[1]
+
+            authentic_token = cls._create_token(user_id, issued_on, nonce)
+            if hmac.compare_digest(
+                authentic_token.encode('utf-8'), token.encode('utf-8')
+            ):
                 return True
 
             return False

programming_language: Python
filename: base_test.py
change_type: ModificationType.MODIFY
diff: @@ -743,7 +743,7 @@ class CsrfTokenManagerTests(test_utils.GenericTestBase):
         self.assertFalse(
             base.CsrfTokenManager.is_csrf_token_valid(uid, 'new_token'))
         self.assertFalse(
-            base.CsrfTokenManager.is_csrf_token_valid(uid, 'new/token'))
+            base.CsrfTokenManager.is_csrf_token_valid(uid, 'a/new/token'))
 
     def test_non_default_csrf_secret_is_used(self) -> None:
         base.CsrfTokenManager.create_csrf_token('uid')

programming_language: Python