articles/systemd-hardening-in-NixOS/example-systemd-service.nix

63 lines
1.6 KiB
Nix

{ pkgs, ... }:
let
service-name = "example-service";
user = "example-service-user";
in
{
users.users = {
${user} = {
group = user;
isNormalUser = true;
createHome = false;
};
};
users.groups.${user} = { };
systemd.services.${service-name} = {
serviceConfig = {
User = user;
Group = user;
# Runtime directory and mode
RuntimeDirectory = service-name;
RuntimeDirectoryMode = "0750";
# State directory and mode
StateDirectory = service-name;
StateDirectoryMode = "0750";
# Cache directory and mode
CacheDirectory = service-name;
CacheDirectoryMode = "0750";
# Logs directory and mode
LogsDirectory = service-name;
LogsDirectoryMode = "0750";
# Configuration directory and mode
ConfigurationDirectory = service-name;
ConfigurationDirectoryMode = "0755";
# Sandboxing
ProtectSystem = "full";
ProtectHome = "read-only";
PrivateTmp = true;
ProtectControlGroups = true;
PrivateMounts = true;
ExecStart = "${pkgs.tmux}/bin/tmux -S /run/${service-name}/tmux.socket new-session -s my-session -d";
ExecStop = "${pkgs.tmux}/bin/tmux -S /run/${service-name}/tmux.socket kill-session -t my-session";
Type = "forking";
};
#confinement.enable = true;
};
networking = {
firewall = {
extraCommands = ''
iptables -t filter -I OUTPUT 1 -m owner --uid-owner ${user} -m state --state NEW -j REJECT
'';
extraStopCommands = ''
iptables -t filter -D OUTPUT 1 -m owner --uid-owner ${user} -m state --state NEW
'';
};
};
}