Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
59 changes: 59 additions & 0 deletions resources/libraries/helper.rb
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
require 'openssl'

module Postgresql
module Helper
def local_routes
Expand All @@ -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 == '<no value>' ? 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')
Expand Down
2 changes: 2 additions & 0 deletions resources/metadata.rb
Original file line number Diff line number Diff line change
Expand Up @@ -6,3 +6,5 @@
license 'AGPL-3.0'
description 'Installs/Configures cookbook-logstash'
version '0.5.4'

depends 'openbao'
65 changes: 52 additions & 13 deletions resources/providers/config.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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
Expand All @@ -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
Expand All @@ -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)
Expand Down
4 changes: 3 additions & 1 deletion resources/scripts/rb_ingest_vuln_cve_pg.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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'],
}
Expand Down
1 change: 1 addition & 0 deletions resources/templates/default/db_redborder_pass.ctmpl.erb
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
{{ with secret "secret/data/db_redborder" }}{{ .Data.data.pass }}{{ end }}
14 changes: 7 additions & 7 deletions resources/templates/default/pg_hba.conf.erb
Original file line number Diff line number Diff line change
@@ -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| %>
Expand All @@ -17,4 +17,4 @@ host redborder redborder <%= x["network"] %> <%= x["mode"] %>
host radius radius <%= x["network"] %> <%= x["mode"] %>
<% end %>
<% end %>
<% end %>
<% end %>
1 change: 1 addition & 0 deletions resources/templates/default/pgpass.ctmpl.erb
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
*:*:*:rep:{{ with secret "secret/data/db_rep" }}{{ .Data.data.pass }}{{ end }}
1 change: 1 addition & 0 deletions resources/templates/default/postgresql.conf.erb
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
23 changes: 23 additions & 0 deletions test/helper_test.rb
Original file line number Diff line number Diff line change
@@ -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
Loading