nixos/postgresql: set up sandboxing

Reduces the general exposure of the postgresql.service through systemd
hardening options.
This commit is contained in:
Martin Weinelt 2024-09-27 19:24:59 +02:00
parent ead36718eb
commit 2ebffcc4c7
No known key found for this signature in database
GPG Key ID: 87C1E9888F856759
2 changed files with 41 additions and 0 deletions

View File

@ -623,7 +623,46 @@ in
TimeoutSec = 120;
ExecStart = "${postgresql}/bin/postgres";
# Hardening
CapabilityBoundingSet = [ "" ];
DevicePolicy = "closed";
PrivateTmp = false; #breaks wal-receiver test
ProtectHome = true;
ProtectSystem = "strict";
MemoryDenyWriteExecute = true;
NoNewPrivileges = true;
LockPersonality = true;
PrivateDevices = true;
PrivateMounts = false; # breaks wal-receiver test
ProcSubset = "pid";
ProtectClock = true;
ProtectControlGroups = true;
ProtectHostname = true;
ProtectKernelLogs = true;
ProtectKernelModules = true;
ProtectKernelTunables = true;
ProtectProc = "invisible";
RemoveIPC = true;
RestrictAddressFamilies = [
"AF_INET"
"AF_INET6"
"AF_NETLINK" # used for network interface enumeration
"AF_UNIX"
];
RestrictNamespaces = true;
RestrictRealtime = true;
RestrictSUIDSGID = true;
SystemCallArchitectures = "native";
SystemCallFilter = [
"@system-service"
"~@privileged @resources"
];
UMask = if groupAccessAvailable then "0027" else "0077";
}
(mkIf (cfg.dataDir != "/var/lib/postgresql") {
ReadWritePaths = [ cfg.dataDir ];
})
(mkIf (cfg.dataDir == "/var/lib/postgresql/${cfg.package.psqlSchema}") {
StateDirectory = "postgresql postgresql/${cfg.package.psqlSchema}";
StateDirectoryMode = if groupAccessAvailable then "0750" else "0700";

View File

@ -126,6 +126,8 @@ let
with subtest("Initdb works"):
machine.succeed("sudo -u postgres initdb -D /tmp/testpostgres2")
machine.log(machine.execute("systemd-analyze security postgresql.service | grep -v ")[1])
machine.shutdown()
'';