diff --git a/resources/libraries/helper.rb b/resources/libraries/helper.rb index bbbe3b9..d37acc3 100644 --- a/resources/libraries/helper.rb +++ b/resources/libraries/helper.rb @@ -1,3 +1,5 @@ +require 'openssl' + module Postgresql module Helper def local_routes @@ -14,6 +16,63 @@ def local_routes routes end + PSQL = '/bin/psql -h 127.0.0.1 -U postgres -d postgres -XAtq'.freeze + + # md5 until no role has an md5 verifier: md5 also accepts SCRAM verifiers + def hba_password_method + out = `#{PSQL} -c "SELECT count(*) FROM pg_authid WHERE rolpassword LIKE 'md5%'" 2>/dev/null`.strip + $?.success? && out == '0' ? 'scram-sha-256' : 'md5' + end + + # built here so the plain password never reaches the server log + def scram_verifier(pass, salt = OpenSSL::Random.random_bytes(16), iterations = 4096) + salted = OpenSSL::KDF.pbkdf2_hmac(pass, salt: salt, iterations: iterations, length: 32, hash: 'sha256') + client = OpenSSL::HMAC.digest('sha256', salted, 'Client Key') + server = OpenSSL::HMAC.digest('sha256', salted, 'Server Key') + b = ->(s) { [s].pack('m0') } + "SCRAM-SHA-256$#{iterations}:#{b.call(salt)}$#{b.call(OpenSSL::Digest::SHA256.digest(client))}:#{b.call(server)}" + end + + def scram_matches?(verifier, pass) + m = /\ASCRAM-SHA-256\$(\d+):([^$]+)\$/.match(verifier) or return false + scram_verifier(pass, m[2].unpack1('m'), m[1].to_i) == verifier + end + + REP_PGPASS = '/run/rb-secrets/postgresql-rep/pgpass'.freeze + + # rep's password from the agent-rendered pgpass; nil until the agent has written it + def rep_password + pass = ::File.read(REP_PGPASS).strip.split(':', 5).last.to_s + pass.empty? || pass == '' ? nil : pass + rescue Errno::ENOENT + nil + end + + # a joining replica: wait for the agent (its delayed restart comes too late), then copy the primary + def sync_from_master(master_ip) + unless rep_password + system('systemctl restart openbao-agent') + 30.times { rep_password ? break : sleep(1) } + end + if !rep_password + Chef::Log.warn('PostgreSQL sync postponed: no rep password in pgpass yet') + elsif !system("rb_sync_from_master.sh #{master_ip}") + Chef::Log.error('rb_sync_from_master.sh failed, retrying on the next run') + end + end + + # SCRAM verifier stored on the primary for rep: nil on a replica or without a server + def rep_verifier_on_primary + out = `#{PSQL} -c "SELECT 'x' || coalesce(rolpassword, '') FROM pg_authid WHERE rolname = 'rep' AND NOT pg_is_in_recovery()" 2>/dev/null` + $?.success? && out.start_with?('x') ? out.strip[1..] : nil + end + + def set_rep_password(pass) + cmd = Mixlib::ShellOut.new("#{PSQL} -v ON_ERROR_STOP=1", input: "ALTER ROLE rep PASSWORD '#{scram_verifier(pass)}';\n").run_command + # no output in the message: psql echoes the statement + raise "ALTER ROLE rep failed (exit #{cmd.exitstatus})" if cmd.error? + end + def find_master_ip cluster_info = node.dig('redborder', 'cluster_info') postgresql_managers = node.dig('redborder', 'managers_per_services', 'postgresql') diff --git a/resources/metadata.rb b/resources/metadata.rb index 911425f..5792027 100644 --- a/resources/metadata.rb +++ b/resources/metadata.rb @@ -6,3 +6,5 @@ license 'AGPL-3.0' description 'Installs/Configures cookbook-logstash' version '0.5.4' + +depends 'openbao' diff --git a/resources/providers/config.rb b/resources/providers/config.rb index 275b383..1e5f6db 100644 --- a/resources/providers/config.rb +++ b/resources/providers/config.rb @@ -7,6 +7,7 @@ begin user = new_resource.user routes = local_routes + sync_pending = '/var/lib/pgsql/data/rb_sync_pending' dnf_package 'postgresql' do action :upgrade @@ -22,6 +23,21 @@ not_if 'getent passwd postgres' end + # before initdb: a joining node needs rep's password to sync + openbao_secret_file 'postgresql-rep' do + source 'pgpass.ctmpl.erb' + cookbook 'postgresql' + destination Postgresql::Helper::REP_PGPASS + selinux_type 'postgresql_var_run_t' # postgres (postgresql_t) cannot read var_run_t: replica sends no password + owner user + group user + mode '0600' + end + + link '/var/lib/pgsql/.pgpass' do + to Postgresql::Helper::REP_PGPASS + end + unless ::File.exist? '/var/lib/pgsql/data/postgresql.conf' Chef::Log.info('Initializing postgresql service') execute 'postgresql_initdb' do @@ -39,28 +55,26 @@ notifies :restart, 'service[postgresql]' end - ruby_block 'sync_if_not_master' do - block do - master_ip = find_master_ip - if master_ip - local_ips = `hostname -I`.split - unless local_ips.include?(master_ip) - system("rb_sync_from_master.sh #{master_ip}") - end - end - end - action :run + file sync_pending do + only_if { (m = find_master_ip) && !`hostname -I`.split.include?(m) } end end + # rb_sync_from_master.sh replaces the data directory, marker included + ruby_block 'sync_if_not_master' do + block { sync_from_master(find_master_ip) } + only_if { ::File.exist?(sync_pending) && find_master_ip } + end + template '/var/lib/pgsql/data/pg_hba.conf' do source 'pg_hba.conf.erb' owner user group user mode '0644' cookbook 'postgresql' - variables(routes: routes, user: user) - notifies :restart, 'service[postgresql]' + variables(routes: routes, method: hba_password_method, + local_ips: `hostname -I`.split.select { |ip| ip.include?('.') } - ['127.0.0.1']) + notifies :reload, 'service[postgresql]' end service 'postgresql' do @@ -70,6 +84,31 @@ action [:start, :enable] end + # primary only: replicas get it through WAL + ruby_block 'Set the PostgreSQL password of rep' do + block { set_rep_password(rep_password) } + sensitive true + ignore_failure true + only_if { rep_password && (v = rep_verifier_on_primary) && !scram_matches?(v, rep_password) } + end + + # postgresql.conf is only written at initdb + psql = Postgresql::Helper::PSQL + execute 'Store new PostgreSQL passwords as SCRAM-SHA-256' do + command "#{psql} -c \"ALTER SYSTEM SET password_encryption = 'scram-sha-256'\" -c 'SELECT pg_reload_conf()'" + only_if "#{psql} -c 'SELECT 1'" + not_if "#{psql} -c 'SHOW password_encryption' | grep -qx scram-sha-256" + end + + openbao_secret_file 'postgresql-db-redborder' do + source 'db_redborder_pass.ctmpl.erb' + cookbook 'postgresql' + destination '/run/rb-secrets/postgresql/db_redborder_pass' + owner 'root' + group 'root' + mode '0600' + end + Chef::Log.info('PostgreSQL cookbook has been processed') rescue => e Chef::Log.error(e.message) diff --git a/resources/scripts/rb_ingest_vuln_cve_pg.rb b/resources/scripts/rb_ingest_vuln_cve_pg.rb index 49490f4..6c2df09 100644 --- a/resources/scripts/rb_ingest_vuln_cve_pg.rb +++ b/resources/scripts/rb_ingest_vuln_cve_pg.rb @@ -32,10 +32,12 @@ def self.redborder_pg_conn .reject(&:empty?) .map { |line| line.split(/:\s+/, 2) } .to_h + pass_file = '/run/rb-secrets/postgresql/db_redborder_pass' + password = File.size?(pass_file) ? File.read(pass_file).strip : databag['pass'] { dbname: databag['database'], user: databag['username'], - password: databag['pass'], + password: password, host: databag['hostname'], port: databag['port'], } diff --git a/resources/templates/default/db_redborder_pass.ctmpl.erb b/resources/templates/default/db_redborder_pass.ctmpl.erb new file mode 100644 index 0000000..53f19ad --- /dev/null +++ b/resources/templates/default/db_redborder_pass.ctmpl.erb @@ -0,0 +1 @@ +{{ with secret "secret/data/db_redborder" }}{{ .Data.data.pass }}{{ end }} \ No newline at end of file diff --git a/resources/templates/default/pg_hba.conf.erb b/resources/templates/default/pg_hba.conf.erb index 87162b4..6f1face 100644 --- a/resources/templates/default/pg_hba.conf.erb +++ b/resources/templates/default/pg_hba.conf.erb @@ -1,13 +1,13 @@ #TYPE DATABASE USER CIDR-ADDRESS METHOD host all all 127.0.0.1/32 trust host all all ::1/128 trust +# This node's own addresses: local processes only +<% @local_ips.each do |ip| %> +host all all <%= ip %>/32 trust +<% end %> <% @routes.each do |r| %> -host all all <%= r.to_s %> trust -host all <%= @user %> <%= r.to_s %> trust -host druid druid <%= r.to_s %> trust -host redborder redborder <%= r.to_s %> trust -host replication rep <%= r.to_s %> trust -host radius radius <%= r.to_s %> trust +host all all <%= r.to_s %> <%= @method %> +host replication rep <%= r.to_s %> <%= @method %> <% end %> <% if !node["redborder"]["manager"].nil? and !node["redborder"]["manager"]["database"].nil? and !node["redborder"]["manager"]["database"]["grant"].nil? %> <% node["redborder"]["manager"]["database"]["grant"].each do |x| %> @@ -17,4 +17,4 @@ host redborder redborder <%= x["network"] %> <%= x["mode"] %> host radius radius <%= x["network"] %> <%= x["mode"] %> <% end %> <% end %> -<% end %> \ No newline at end of file +<% end %> diff --git a/resources/templates/default/pgpass.ctmpl.erb b/resources/templates/default/pgpass.ctmpl.erb new file mode 100644 index 0000000..26611ac --- /dev/null +++ b/resources/templates/default/pgpass.ctmpl.erb @@ -0,0 +1 @@ +*:*:*:rep:{{ with secret "secret/data/db_rep" }}{{ .Data.data.pass }}{{ end }} diff --git a/resources/templates/default/postgresql.conf.erb b/resources/templates/default/postgresql.conf.erb index 06c275b..fbe0d58 100644 --- a/resources/templates/default/postgresql.conf.erb +++ b/resources/templates/default/postgresql.conf.erb @@ -6,6 +6,7 @@ # Memory asigned: 1449 listen_addresses = '*' port = 5432 +password_encryption = scram-sha-256 max_connections = 1000 shared_buffers = 362MB work_mem = 8MB # min 64kB diff --git a/test/helper_test.rb b/test/helper_test.rb new file mode 100644 index 0000000..209f040 --- /dev/null +++ b/test/helper_test.rb @@ -0,0 +1,23 @@ +# ruby test/helper_test.rb +require 'minitest/autorun' +require_relative '../resources/libraries/helper' + +class HelperTest < Minitest::Test + include Postgresql::Helper + + def test_scram_verifier_matches_postgresql_format + # same vector as redborder-openbao rotate_test.go + assert_equal 'SCRAM-SHA-256$4096:MDEyMzQ1Njc4OWFiY2RlZg==$1asHMbH2my37rP6NwUFN+2R8TdQH62n1sUt37vYmrdg=:NzWfkwfUXAEhu4qk7VI4+OobFAOX1J1vq5shICwNaKc=', + scram_verifier('secretpass', '0123456789abcdef') + refute_equal scram_verifier('x'), scram_verifier('x') + end + + def test_scram_matches + v = scram_verifier('secretpass') + assert scram_matches?(v, 'secretpass') + refute scram_matches?(v, 'other') + refute scram_matches?('', 'secretpass') + refute scram_matches?('md5abc', 'secretpass') + assert scram_matches?(scram_verifier('p', 'saltsaltsaltsalt', 10), 'p') + end +end