A platform for community discussion. Free, open, simple.
DEV: Bump `landlock`, refactor, and add problem check (#42049)
David Taylor226adb08ea78
diff --git a/Gemfile.lock b/Gemfile.lockindex a4e2e8af47f..ccbaf6c736a 100644--- a/Gemfile.lock+++ b/Gemfile.lock@@ -314,7 +314,7 @@ GEMsimpleidn (~> 0.2)jwt (2.10.1)base64- landlock (0.2)+ landlock (0.3)language_server-protocol (3.17.0.5)libv8-node (24.12.0.1-aarch64-linux)libv8-node (24.12.0.1-aarch64-linux-musl)@@ -1105,7 +1105,7 @@ CHECKSUMSjson_completer (1.2.0) sha256=4665749172634eccb208c562eb59ea81dd7a612a1fa9a36df441ac473ff177b1json_schemer (2.5.0) sha256=2f01fb4cce721a4e08dd068fc2030cffd0702a7f333f1ea2be6e8991f00ae396jwt (2.10.1) sha256=e6424ae1d813f63e761a04d6284e10e7ec531d6f701917fadcd0d9b2deaf1cc5- landlock (0.2) sha256=9bb86d7d12b16485b278ba575d49f55b730089c7a3d0f45a769fe4d7384d5e55+ landlock (0.3) sha256=841ae1ef1318082a485ae919b6a481ceb9c2d3ac9294ada27e2a3c529446b23clanguage_server-protocol (3.17.0.5) sha256=fd1e39a51a28bf3eec959379985a72e296e9f9acfce46f6a79d31ca8760803cclibv8-node (24.12.0.1-aarch64-linux) sha256=22bd0246cde85d70c88cf772727ac3677a20ac1d169105f82efe5f1f7c39f755libv8-node (24.12.0.1-aarch64-linux-musl) sha256=791b5960f79525e87d1bd1e5f2bf3715ef2a38bac6c97f297853e98a8411ba89diff --git a/app/models/problem_check.rb b/app/models/problem_check.rbindex becaa627c31..6b39535cc72 100644--- a/app/models/problem_check.rb+++ b/app/models/problem_check.rb@@ -80,6 +80,7 @@ class ProblemCheckProblemCheck::GroupEmailCredentials,ProblemCheck::HostNames,ProblemCheck::ImageMagick,+ ProblemCheck::Landlock,ProblemCheck::MissingAwsSnsTopicArn,ProblemCheck::MissingMailgunApiKey,ProblemCheck::OutOfDateThemes,diff --git a/app/services/problem_check/landlock.rb b/app/services/problem_check/landlock.rbnew file mode 100644index 00000000000..316249be097--- /dev/null+++ b/app/services/problem_check/landlock.rb@@ -0,0 +1,14 @@+# frozen_string_literal: true++require "discourse/safe_exec"++class ProblemCheck::Landlock < ProblemCheck+ self.priority = "high"++ def call+ return no_problem if !Rails.env.production?+ return no_problem if Discourse::SafeExec.landlock_supported?++ problem+ end+enddiff --git a/config/locales/server.en.yml b/config/locales/server.en.ymlindex 1e2e00bc812..1b4c47b52fe 100644--- a/config/locales/server.en.yml+++ b/config/locales/server.en.yml@@ -1840,6 +1840,7 @@ en:group_email_credentials: 'There was an issue with the email credentials for the group <a href="%{base_path}/g/%{group_name}/manage/email">%{group_full_name}</a>. No emails will be sent from the group inbox until this problem is addressed. %{error}'upcoming_change_stable_opted_out: 'Your site has opted-out of the "%{upcoming_change}" upcoming change. This change has now reached the "Stable" status and may soon be removed or made permanent. Visit <a href="%{base_path}/admin/config/upcoming-changes">the upcoming changes page</a> to review details about this change.'content_security_policy_disabled: "The content-security-policy feature has been disabled. This is an important security feature, and should never be disabled in production environments. <a href='%{base_path}/admin/site_settings/category/all_results?filter=content_security_policy'>Re-enable it here</a>."+ landlock: "Landlock sandboxing is unavailable in this hosting environment, so external commands run without filesystem and network isolation. This is an important security protection that should not be missing in production. Use a Linux kernel with Landlock support (5.13 or later) to restore it."rails_env: "Your server is running in %{env} mode."host_names: "Your config/database.yml file is using the default localhost hostname. Update it to use your site's hostname."sidekiq_check: 'Sidekiq is not running. Many tasks, like sending emails, are executed asynchronously by Sidekiq. Please ensure at least one Sidekiq process is running. <a href="https://github.com/mperham/sidekiq" target="_blank">Learn about Sidekiq here</a>.'diff --git a/lib/discourse.rb b/lib/discourse.rbindex f5b19044a3d..d89f932c9d6 100644--- a/lib/discourse.rb+++ b/lib/discourse.rb@@ -164,6 +164,7 @@ module Discoursefailure_message: "",success_status_codes: [0],chdir: ".",+ unsetenv_others: false,unsafe_shell: false)env = nil@@ -183,7 +184,10 @@ module Discourseargs = commandargs = [env] + command if env- stdout, stderr, status = Open3.capture3(*args, chdir: chdir)++ spawn_options = { chdir: chdir }+ spawn_options[:unsetenv_others] = true if unsetenv_others+ stdout, stderr, status = Open3.capture3(*args, **spawn_options)if !status.exited? || !success_status_codes.include?(status.exitstatus)message = [command.join(" "), failure_message, stderr].filter(&:present?).join("\n")diff --git a/lib/discourse/safe_exec.rb b/lib/discourse/safe_exec.rbindex 6c4fda6ac54..c4b8a5e3ecb 100644--- a/lib/discourse/safe_exec.rb+++ b/lib/discourse/safe_exec.rb@@ -1,20 +1,11 @@# frozen_string_literal: true-begin- require "landlock"-rescue LoadError-end+require "landlock"module Discourseclass SafeExecDEFAULT_READ_PATHS = %w[/bin /etc /lib /lib64 /usr].freezeDEFAULT_EXECUTE_PATHS = %w[/bin /lib /lib64 /usr].freeze- LANDLOCK_COMMAND_ERROR =- if defined?(::Landlock::SafeExec::CommandError)- ::Landlock::SafeExec::CommandError- else- Class.new(StandardError)- enddef self.capture(*command,@@ -34,20 +25,20 @@ module Discoursemax_output_bytes: nil,truncate_output: false)- if defined?(::Landlock::SafeExec)+ if ::Landlock.supported?result =- ::Landlock::SafeExec.capture(- *command,+ ::Landlock.capture(+ command,read: read,write: write,execute: execute,timeout: timeout,failure_message: failure_message,success_status_codes: success_status_codes,- env: env || {},- inherit_env: !unsetenv_others,+ env: env,+ unsetenv_others: unsetenv_others,chdir: chdir,- connect_tcp: connect_tcp,+ connect_tcp: Array(connect_tcp),bind_tcp: bind_tcp,rlimits: rlimits,seccomp_deny_network: seccomp_deny_network,@@ -70,9 +61,10 @@ module Discoursefailure_message: failure_message,success_status_codes: success_status_codes,chdir: chdir || ".",+ unsetenv_others: unsetenv_others,)end- rescue LANDLOCK_COMMAND_ERROR => e+ rescue ::Landlock::CommandError => eraise Discourse::Utils::CommandError.new(e.message,stdout: e.stdout,@@ -82,23 +74,15 @@ module Discourseenddef self.landlock_supported?- defined?(::Landlock::SafeExec) && ::Landlock::SafeExec.supported?+ ::Landlock.supported?enddef self.default_read_paths- if defined?(::Landlock::SafeExec)- ::Landlock::SafeExec.default_read_paths- else- existing_paths(DEFAULT_READ_PATHS)- end+ existing_paths(DEFAULT_READ_PATHS)enddef self.default_execute_paths- if defined?(::Landlock::SafeExec)- ::Landlock::SafeExec.default_execute_paths- else- existing_paths(DEFAULT_EXECUTE_PATHS)- end+ existing_paths(DEFAULT_EXECUTE_PATHS)enddef self.existing_paths(paths)diff --git a/spec/lib/discourse/safe_exec_spec.rb b/spec/lib/discourse/safe_exec_spec.rbindex 8e1e5235303..4604323e951 100644--- a/spec/lib/discourse/safe_exec_spec.rb+++ b/spec/lib/discourse/safe_exec_spec.rb@@ -4,18 +4,19 @@ require "discourse/safe_exec"RSpec.describe Discourse::SafeExec dodescribe ".capture" do- it "delegates sandboxed execution to Landlock::SafeExec" do+ it "delegates sandboxed execution to Landlock" dostatus = instance_double(Process::Status, exited?: true, exitstatus: 0)result =instance_double(- Landlock::SafeExec::Result,+ Landlock::CaptureResult,stdout: "hello\n",stderr: "",status: status,output_truncated?: false,)- allow(Landlock::SafeExec).to receive(:capture).and_return(result)+ allow(Landlock).to receive(:supported?).and_return(true)+ allow(Landlock).to receive(:capture).and_return(result)expect(described_class.capture(@@ -37,9 +38,8 @@ RSpec.describe Discourse::SafeExec do),).to eq("hello\n")- expect(Landlock::SafeExec).to have_received(:capture).with(- "echo",- "hello",+ expect(Landlock).to have_received(:capture).with(+ %w[echo hello],read: ["/tmp/input"],write: [],execute: described_class.default_execute_paths,@@ -49,9 +49,9 @@ RSpec.describe Discourse::SafeExec doenv: {"PATH" => ENV["PATH"].to_s,},- inherit_env: false,+ unsetenv_others: true,chdir: nil,- connect_tcp: nil,+ connect_tcp: [],bind_tcp: [],rlimits: {cpu_seconds: 1,@@ -66,14 +66,15 @@ RSpec.describe Discourse::SafeExec dostatus = instance_double(Process::Status, exited?: true, exitstatus: 1)result =instance_double(- Landlock::SafeExec::Result,+ Landlock::CaptureResult,stdout: "",stderr: "nope",status: status,output_truncated?: false,)- allow(Landlock::SafeExec).to receive(:capture).and_return(result)+ allow(Landlock).to receive(:supported?).and_return(true)+ allow(Landlock).to receive(:capture).and_return(result)expect { described_class.capture("false", failure_message: "failed") }.to raise_error(Discourse::Utils::CommandError,@@ -81,24 +82,81 @@ RSpec.describe Discourse::SafeExec do)end+ it "converts Landlock::CommandError into a Discourse command error" do+ status = instance_double(Process::Status)++ allow(Landlock).to receive(:supported?).and_return(true)+ allow(Landlock).to receive(:capture).and_raise(+ Landlock::CommandError.new("boom", stdout: "out", stderr: "err", status: status),+ )++ expect { described_class.capture("tool") }.to raise_error(+ Discourse::Utils::CommandError,+ /boom/,+ )+ end+it "returns truncated stdout without checking the terminated status" dostatus = instance_double(Process::Status, exited?: false, exitstatus: nil)result =instance_double(- Landlock::SafeExec::Result,+ Landlock::CaptureResult,stdout: "x" * 1024,stderr: "",status: status,output_truncated?: true,)- allow(Landlock::SafeExec).to receive(:capture).and_return(result)+ allow(Landlock).to receive(:supported?).and_return(true)+ allow(Landlock).to receive(:capture).and_return(result)expect(described_class.capture("tool", truncate_output: true)).to eq("x" * 1024)end+ it "runs unsandboxed when Landlock is unavailable on the system" do+ allow(Landlock).to receive(:supported?).and_return(false)+ allow(Discourse::Utils).to receive(:execute_command).and_return("hello\n")++ expect(described_class.capture("echo", "hello", chdir: "/tmp")).to eq("hello\n")++ expect(Discourse::Utils).to have_received(:execute_command).with(+ "echo",+ "hello",+ timeout: nil,+ failure_message: "",+ success_status_codes: [0],+ chdir: "/tmp",+ unsetenv_others: false,+ )+ end++ it "still strips the child environment in the unsandboxed fallback" do+ allow(Landlock).to receive(:supported?).and_return(false)++ previous_secret = ENV["SAFE_EXEC_SECRET"]+ ENV["SAFE_EXEC_SECRET"] = "hidden"+ output =+ described_class.capture(+ "sh",+ "-c",+ "printf '%s' \"${SAFE_EXEC_SECRET-unset}\"",+ env: {+ "PATH" => ENV["PATH"].to_s,+ },+ unsetenv_others: true,+ )++ expect(output).to eq("unset")+ ensure+ if previous_secret.nil?+ ENV.delete("SAFE_EXEC_SECRET")+ else+ ENV["SAFE_EXEC_SECRET"] = previous_secret+ end+ end+it "captures stdout from a landlocked subprocess" do- skip "Landlock SafeExec is not supported" if !described_class.landlock_supported?+ skip "Landlock is not supported" if !described_class.landlock_supported?output =described_class.capture(@@ -112,7 +170,7 @@ RSpec.describe Discourse::SafeExec doendit "denies access to paths outside of the Landlock policy" do- skip "Landlock SafeExec is not supported" if !described_class.landlock_supported?+ skip "Landlock is not supported" if !described_class.landlock_supported?Tempfile.create("safe-exec") do |tempfile|tempfile.write("secret")@@ -130,6 +188,8 @@ RSpec.describe Discourse::SafeExec doendit "can clear the child environment" do+ skip "Landlock is not supported" if !described_class.landlock_supported?+previous_secret = ENV["SAFE_EXEC_SECRET"]ENV["SAFE_EXEC_SECRET"] = "hidden"output =@@ -155,7 +215,7 @@ RSpec.describe Discourse::SafeExec doendit "denies network syscalls when requested" do- skip "Landlock SafeExec is not supported" if !described_class.landlock_supported?+ skip "Landlock is not supported" if !described_class.landlock_supported?expect {described_class.capture(@@ -175,22 +235,38 @@ RSpec.describe Discourse::SafeExec doendit "terminates commands that exceed the output limit" do+ skip "Landlock is not supported" if !described_class.landlock_supported?+expect {described_class.capture(RbConfig.ruby,"-e","STDOUT.write('x' * 2048)",+ read: described_class.default_read_paths,+ execute: described_class.default_execute_paths,+ env: {+ "PATH" => ENV["PATH"].to_s,+ },+ unsetenv_others: true,max_output_bytes: 1024,)}.to raise_error(Discourse::Utils::CommandError, /output exceeded 1024 bytes/)endit "truncates commands that exceed the output limit when requested" do+ skip "Landlock is not supported" if !described_class.landlock_supported?+output =described_class.capture(RbConfig.ruby,"-e","STDOUT.write('x' * 2048)",+ read: described_class.default_read_paths,+ execute: described_class.default_execute_paths,+ env: {+ "PATH" => ENV["PATH"].to_s,+ },+ unsetenv_others: true,max_output_bytes: 1024,truncate_output: true,)diff --git a/spec/services/problem_check/landlock_spec.rb b/spec/services/problem_check/landlock_spec.rbnew file mode 100644index 00000000000..049afc8a24a--- /dev/null+++ b/spec/services/problem_check/landlock_spec.rb@@ -0,0 +1,39 @@+# frozen_string_literal: true++RSpec.describe ProblemCheck::Landlock do+ subject(:check) { described_class.new }++ describe ".call" do+ before do+ Rails.stubs(env: ActiveSupport::StringInquirer.new(environment))+ Discourse::SafeExec.stubs(landlock_supported?: supported)+ end++ context "when running in production" do+ let(:environment) { "production" }++ context "when Landlock is supported" do+ let(:supported) { true }++ it { expect(check).to be_chill_about_it }+ end++ context "when Landlock is not supported" do+ let(:supported) { false }++ it do+ expect(check).to have_a_problem.with_priority("high").with_message(+ "Landlock sandboxing is unavailable in this hosting environment, so external commands run without filesystem and network isolation. This is an important security protection that should not be missing in production. Use a Linux kernel with Landlock support (5.13 or later) to restore it.",+ )+ end+ end+ end++ context "when not running in production" do+ let(:environment) { "development" }+ let(:supported) { false }++ it { expect(check).to be_chill_about_it }+ end+ end+end