CVE-2023-37467 (published 2023-07-28T15:15Z)

Discourse is an open source discussion platform. Prior to version 3.1.0.beta7 of the `beta` and `tests-passed` branches, a CSP (Content Security Policy) nonce reuse vulnerability was discovered could allow cross-site scripting (XSS) attacks to bypass CSP protection for anonymous (i.e. unauthenticated) users. There are no known XSS vectors at the moment, but should one be discovered, this vulnerability would allow the XSS attack to bypass CSP and execute successfully. This vulnerability isn't applicable to logged-in users. Version 3.1.0.beta7 contains a patch. The stable branch doesn't have this vulnerability. A workaround to prevent the vulnerability is to disable Google Tag Manager, i.e., unset the `gtm container id` setting.

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

Weakness information:
cwe_id: CWE-79
cwe_name: Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')
description: The product does not neutralize or incorrectly neutralizes user-controllable input before it is placed in output that is used as a web page that is served to other users.
extended_description: 
            Cross-site scripting (XSS) vulnerabilities occur when:
            
               Untrusted data enters a web application, typically from a web request.
               The web application dynamically generates a web page that contains this untrusted data.
               During page generation, the application does not prevent the data from containing content that is executable by a web browser, such as JavaScript, HTML tags, HTML attributes, mouse events, Flash, ActiveX, etc.
               A victim visits the generated web page through a web browser, which contains malicious script that was injected using the untrusted data.
               Since the script comes from a web page that was sent by the web server, the victim's web browser executes the malicious script in the context of the web server's domain.
               This effectively violates the intention of the web browser's same-origin policy, which states that scripts in one domain should not be able to access resources or run code in a different domain.
            
            There are three main kinds of XSS:
            
               
                  Type 1: Reflected XSS (or Non-Persistent) - 
         			The server reads data directly from the HTTP request and reflects it back in the HTTP response. Reflected XSS exploits occur when an attacker causes a victim to supply dangerous content to a vulnerable web application, which is then reflected back to the victim and executed by the web browser. The most common mechanism for delivering malicious content is to include it as a parameter in a URL that is posted publicly or e-mailed directly to the victim. URLs constructed in this manner constitute the core of many phishing schemes, whereby an attacker convinces a victim to visit a URL that refers to a vulnerable site. After the site reflects the attacker's content back to the victim, the content is executed by the victim's browser.
               
                  Type 2: Stored XSS (or Persistent) - 
               The application stores dangerous data in a database, message forum, visitor log, or other trusted data store. At a later time, the dangerous data is subsequently read back into the application and included in dynamic content. From an attacker's perspective, the optimal place to inject malicious content is in an area that is displayed to either many users or particularly interesting users. Interesting users typically have elevated privileges in the application or interact with sensitive data that is valuable to the attacker. If one of these users executes malicious content, the attacker may be able to perform privileged operations on behalf of the user or gain access to sensitive data belonging to the user. For example, the attacker might inject XSS into a log message, which might not be handled properly when an administrator views the logs.
            
               
                  Type 0: DOM-Based XSS - 
               In DOM-based XSS, the client performs the injection of XSS into the page; in the other types, the server performs the injection. DOM-based XSS generally involves server-controlled, trusted script that is sent to the client, such as Javascript that performs sanity checks on a form before the user submits it. If the server-supplied script processes user-supplied data and then injects it back into the web page (such as with dynamic HTML), then DOM-based XSS is possible.
            
            
            Once the malicious script is injected, the attacker can perform a variety of malicious activities. The attacker could transfer private information, such as cookies that may include session information, from the victim's machine to the attacker. The attacker could send malicious requests to a web site on behalf of the victim, which could be especially dangerous to the site if the victim has administrator privileges to manage that site. Phishing attacks could be used to emulate trusted web sites and trick the victim into entering a password, allowing the attacker to compromise the victim's account on that web site. Finally, the script could exploit a vulnerability in the web browser itself possibly taking over the victim's machine, sometimes referred to as "drive-by hacking."
            In many cases, the attack can be launched without the victim even being aware of it. Even with careful users, attackers frequently use a variety of methods to encode the malicious portion of the attack, such as URL encoding or Unicode, so the request looks less suspicious.
         
         

Fix information:
repo_url: https://github.com/discourse/discourse
commit_details: repo_url: https://github.com/discourse/discourse
author: OsamaSayegh
author_date: 2023-07-28 12:53:44+01:00
msg: SECURITY: Don't reuse CSP nonce between anonymous requests
repository: repo_url: https://github.com/discourse/discourse
repo_name: discourse/discourse
description: A platform for community discussion. Free, open, simple.
repo_language: Ruby
owner: discourse
file_changes: filename: application_helper.rb
change_type: ModificationType.MODIFY
diff: @@ -64,8 +64,10 @@ module ApplicationHelper
     google_universal_analytics_json
   end
 
-  def self.google_tag_manager_nonce(env)
-    env[:discourse_content_security_policy_nonce] ||= SecureRandom.hex
+  def google_tag_manager_nonce_placeholder
+    placeholder = "[[csp_nonce_placeholder_#{SecureRandom.hex}]]"
+    response.headers["Discourse-GTM-Nonce-Placeholder"] = placeholder
+    placeholder
   end
 
   def shared_session_key

programming_language: Ruby
filename: _google_tag_manager_head.html.erb
change_type: ModificationType.MODIFY
diff: @@ -1,6 +1,6 @@
 <meta id="data-google-tag-manager"
   data-data-layer="<%= google_tag_manager_json %>"
-  data-nonce="<%= ApplicationHelper.google_tag_manager_nonce(request.env) %>"
+  data-nonce="<%= google_tag_manager_nonce_placeholder %>"
   data-container-id="<%= SiteSetting.gtm_container_id %>" />
 
 <%= preload_script 'google-tag-manager' %>

programming_language: Batchfile
filename: application.rb
change_type: ModificationType.MODIFY
diff: @@ -167,6 +167,9 @@ module Discourse
     config.middleware.swap ActionDispatch::ContentSecurityPolicy::Middleware,
                            ContentSecurityPolicy::Middleware
 
+    require "middleware/gtm_script_nonce_injector"
+    config.middleware.insert_after(ActionDispatch::Flash, Middleware::GtmScriptNonceInjector)
+
     require "middleware/discourse_public_exceptions"
     config.exceptions_app = Middleware::DiscoursePublicExceptions.new(Rails.public_path)
 

programming_language: Ruby
filename: 099-anon-cache.rb
change_type: ModificationType.MODIFY
diff: @@ -6,10 +6,11 @@ enabled =
   if Rails.configuration.respond_to?(:enable_anon_caching)
     Rails.configuration.enable_anon_caching
   else
-    Rails.env.production?
+    Rails.env.production? || Rails.env.test?
   end
 
 if !ENV["DISCOURSE_DISABLE_ANON_CACHE"] && enabled
   # in an ideal world this is position 0, but mobile detection uses ... session and request and params
-  Rails.configuration.middleware.insert_after ActionDispatch::Flash, Middleware::AnonymousCache
+  Rails.configuration.middleware.insert_after Middleware::GtmScriptNonceInjector,
+                                              Middleware::AnonymousCache
 end

programming_language: Ruby
filename: content_security_policy.rb
change_type: ModificationType.MODIFY
diff: @@ -4,13 +4,13 @@ require "content_security_policy/extension"
 
 class ContentSecurityPolicy
   class << self
-    def policy(theme_id = nil, env: {}, base_url: Discourse.base_url, path_info: "/")
-      new.build(theme_id, env: env, base_url: base_url, path_info: path_info)
+    def policy(theme_id = nil, base_url: Discourse.base_url, path_info: "/")
+      new.build(theme_id, base_url: base_url, path_info: path_info)
     end
   end
 
-  def build(theme_id, env: {}, base_url:, path_info: "/")
-    builder = Builder.new(base_url: base_url, env: env)
+  def build(theme_id, base_url:, path_info: "/")
+    builder = Builder.new(base_url: base_url)
 
     Extension.theme_extensions(theme_id).each { |extension| builder << extension }
     Extension.plugin_extensions.each { |extension| builder << extension }

programming_language: Ruby
filename: builder.rb
change_type: ModificationType.MODIFY
diff: @@ -25,8 +25,8 @@ class ContentSecurityPolicy
       style_src
     ].freeze
 
-    def initialize(base_url:, env: {})
-      @directives = Default.new(base_url: base_url, env: env).directives
+    def initialize(base_url:)
+      @directives = Default.new(base_url: base_url).directives
       @base_url = base_url
     end
 

programming_language: Ruby
filename: default.rb
change_type: ModificationType.MODIFY
diff: @@ -5,9 +5,8 @@ class ContentSecurityPolicy
   class Default
     attr_reader :directives
 
-    def initialize(base_url:, env: {})
+    def initialize(base_url:)
       @base_url = base_url
-      @env = env
       @directives =
         {}.tap do |directives|
           directives[:upgrade_insecure_requests] = [] if SiteSetting.force_https
@@ -86,7 +85,6 @@ class ContentSecurityPolicy
         end
         if SiteSetting.gtm_container_id.present?
           sources << "https://www.googletagmanager.com/gtm.js"
-          sources << "'nonce-#{ApplicationHelper.google_tag_manager_nonce(@env)}'"
         end
 
         sources << "'#{SplashScreenHelper.fingerprint}'" if SiteSetting.splash_screen

programming_language: Ruby
filename: middleware.rb
change_type: ModificationType.MODIFY
diff: @@ -21,13 +21,11 @@ class ContentSecurityPolicy
 
       headers["Content-Security-Policy"] = policy(
         theme_id,
-        env: env,
         base_url: base_url,
         path_info: env["PATH_INFO"],
       ) if SiteSetting.content_security_policy
       headers["Content-Security-Policy-Report-Only"] = policy(
         theme_id,
-        env: env,
         base_url: base_url,
         path_info: env["PATH_INFO"],
       ) if SiteSetting.content_security_policy_report_only

programming_language: Ruby
filename: anonymous_cache.rb
change_type: ModificationType.MODIFY
diff: @@ -43,6 +43,21 @@ module Middleware
       env["ANON_CACHE_DURATION"] = duration
     end
 
+    def self.clear_all_cache!
+      if Rails.env.production?
+        raise "for perf reasons, clear_all_cache! cannot be used in production."
+      end
+      Discourse.redis.keys("ANON_CACHE_*").each { |k| Discourse.redis.del(k) }
+    end
+
+    def self.disable_anon_cache
+      @@disabled = true
+    end
+
+    def self.enable_anon_cache
+      @@disabled = false
+    end
+
     # This gives us an API to insert anonymous cache segments
     class Helper
       RACK_SESSION = "rack.session"
@@ -232,7 +247,10 @@ module Middleware
       end
 
       def cacheable?
-        !!(!has_auth_cookie? && get? && no_cache_bypass)
+        !!(
+          GlobalSetting.anon_cache_store_threshold > 0 && !has_auth_cookie? && get? &&
+            no_cache_bypass
+        )
       end
 
       def compress(val)
@@ -326,6 +344,8 @@ module Middleware
     PAYLOAD_INVALID_REQUEST_METHODS = %w[GET HEAD]
 
     def call(env)
+      return @app.call(env) if defined?(@@disabled) && @@disabled
+
       if PAYLOAD_INVALID_REQUEST_METHODS.include?(env[Rack::REQUEST_METHOD]) &&
            env[Rack::RACK_INPUT].size > 0
         return 413, { "Cache-Control" => "private, max-age=0, must-revalidate" }, []

programming_language: Ruby
filename: gtm_script_nonce_injector.rb
change_type: ModificationType.ADD
diff: @@ -0,0 +1,26 @@
+# frozen_string_literal: true
+
+module Middleware
+  class GtmScriptNonceInjector
+    def initialize(app, settings = {})
+      @app = app
+    end
+
+    def call(env)
+      status, headers, response = @app.call(env)
+
+      if nonce_placeholder = headers.delete("Discourse-GTM-Nonce-Placeholder")
+        nonce = SecureRandom.hex
+        parts = []
+        response.each { |part| parts << part.to_s.sub(nonce_placeholder, nonce) }
+        %w[Content-Security-Policy Content-Security-Policy-Report-Only].each do |name|
+          next if headers[name].blank?
+          headers[name] = headers[name].sub("script-src ", "script-src 'nonce-#{nonce}' ")
+        end
+        [status, headers, parts]
+      else
+        [status, headers, response]
+      end
+    end
+  end
+end

programming_language: Ruby
filename: content_security_policy_spec.rb
change_type: ModificationType.MODIFY
diff: @@ -106,7 +106,9 @@ RSpec.describe ContentSecurityPolicy do
 
       script_srcs = parse(policy)["script-src"]
       expect(script_srcs).to include("https://www.googletagmanager.com/gtm.js")
-      expect(script_srcs.to_s).to include("nonce-")
+      # nonce is added by the GtmScriptNonceInjector middleware to prevent the
+      # nonce from getting cached by AnonymousCache
+      expect(script_srcs.to_s).not_to include("nonce-")
     end
 
     it "allowlists CDN assets when integrated" do

programming_language: Ruby
filename: anonymous_cache_spec.rb
change_type: ModificationType.MODIFY
diff: @@ -3,6 +3,8 @@
 RSpec.describe Middleware::AnonymousCache do
   let(:middleware) { Middleware::AnonymousCache.new(lambda { |_| [200, {}, []] }) }
 
+  before { Middleware::AnonymousCache.enable_anon_cache }
+
   def env(opts = {})
     create_request_env(path: opts.delete(:path) || "http://test.com/path?bla=1").merge(opts)
   end

programming_language: Ruby
filename: request_tracker_spec.rb
change_type: ModificationType.MODIFY
diff: @@ -677,6 +677,8 @@ RSpec.describe Middleware::RequestTracker do
     after { Middleware::RequestTracker.unregister_detailed_request_logger(logger) }
 
     it "can report data from anon cache" do
+      Middleware::AnonymousCache.enable_anon_cache
+
       cache = Middleware::AnonymousCache.new(app([200, {}, ["i am a thing"]]))
       tracker = Middleware::RequestTracker.new(cache)
 

programming_language: Ruby
filename: rails_helper.rb
change_type: ModificationType.MODIFY
diff: @@ -149,6 +149,8 @@ module TestSetup
     BadgeGranter.disable_queue
 
     OmniAuth.config.test_mode = false
+
+    Middleware::AnonymousCache.disable_anon_cache
   end
 end
 

programming_language: Ruby
filename: application_controller_spec.rb
change_type: ModificationType.MODIFY
diff: @@ -637,36 +637,63 @@ RSpec.describe ApplicationController do
 
     it "when GTM is enabled it adds the same nonce to the policy and the GTM tag" do
       SiteSetting.content_security_policy = true
+      SiteSetting.content_security_policy_report_only = true
       SiteSetting.gtm_container_id = "GTM-ABCDEF"
 
       get "/latest"
 
-      expect(response.headers).to include("Content-Security-Policy")
       script_src = parse(response.headers["Content-Security-Policy"])["script-src"]
+      report_only_script_src =
+        parse(response.headers["Content-Security-Policy-Report-Only"])["script-src"]
+
       nonce = extract_nonce_from_script_src(script_src)
+      report_only_nonce = extract_nonce_from_script_src(report_only_script_src)
+
+      expect(nonce).to eq(report_only_nonce)
 
       gtm_meta_tag = Nokogiri::HTML5.fragment(response.body).css("#data-google-tag-manager").first
       expect(gtm_meta_tag["data-nonce"]).to eq(nonce)
     end
 
-    it "doesn't reuse CSP nonces between requests" do
+    it "doesn't reuse nonces between requests" do
+      global_setting :anon_cache_store_threshold, 1
+      Middleware::AnonymousCache.enable_anon_cache
+      Middleware::AnonymousCache.clear_all_cache!
+
       SiteSetting.content_security_policy = true
+      SiteSetting.content_security_policy_report_only = true
       SiteSetting.gtm_container_id = "GTM-ABCDEF"
 
       get "/latest"
 
-      expect(response.headers).to include("Content-Security-Policy")
+      expect(response.headers["X-Discourse-Cached"]).to eq("store")
+      expect(response.headers).not_to include("Discourse-GTM-Nonce-Placeholder")
+
       script_src = parse(response.headers["Content-Security-Policy"])["script-src"]
+      report_only_script_src =
+        parse(response.headers["Content-Security-Policy-Report-Only"])["script-src"]
+
       first_nonce = extract_nonce_from_script_src(script_src)
+      first_report_only_nonce = extract_nonce_from_script_src(report_only_script_src)
+
+      expect(first_nonce).to eq(first_report_only_nonce)
 
       gtm_meta_tag = Nokogiri::HTML5.fragment(response.body).css("#data-google-tag-manager").first
       expect(gtm_meta_tag["data-nonce"]).to eq(first_nonce)
 
       get "/latest"
 
-      expect(response.headers).to include("Content-Security-Policy")
+      expect(response.headers["X-Discourse-Cached"]).to eq("true")
+      expect(response.headers).not_to include("Discourse-GTM-Nonce-Placeholder")
+
       script_src = parse(response.headers["Content-Security-Policy"])["script-src"]
+      report_only_script_src =
+        parse(response.headers["Content-Security-Policy-Report-Only"])["script-src"]
+
       second_nonce = extract_nonce_from_script_src(script_src)
+      second_report_only_nonce = extract_nonce_from_script_src(report_only_script_src)
+
+      expect(second_nonce).to eq(second_report_only_nonce)
 
       expect(first_nonce).not_to eq(second_nonce)
       gtm_meta_tag = Nokogiri::HTML5.fragment(response.body).css("#data-google-tag-manager").first

programming_language: Ruby