diff --git a/nixos/modules/services/databases/postgresql.nix b/nixos/modules/services/databases/postgresql.nix index ceaccde813a0..19537b8ea3c9 100644 --- a/nixos/modules/services/databases/postgresql.nix +++ b/nixos/modules/services/databases/postgresql.nix @@ -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"; diff --git a/nixos/tests/postgresql.nix b/nixos/tests/postgresql.nix index c0dd24cf6ad2..ce16e54edf66 100644 --- a/nixos/tests/postgresql.nix +++ b/nixos/tests/postgresql.nix @@ -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() '';