HxHippy

Service Hardening

Secure configuration of common system services.

Last updated: 2025-01-15

Service Hardening Guide

Properly configured services reduce attack surface and limit damage from compromises.

Systemd Security Features

Service Sandboxing

# Example: /etc/systemd/system/myapp.service.d/override.conf
[Service]
# User and group
User=myapp
Group=myapp
DynamicUser=true

# Filesystem access
ProtectSystem=strict
ProtectHome=true
PrivateTmp=true
ReadWritePaths=/var/lib/myapp

# Network isolation
PrivateNetwork=false
RestrictAddressFamilies=AF_INET AF_INET6

# Process isolation
NoNewPrivileges=true
ProtectKernelTunables=true
ProtectKernelModules=true
ProtectControlGroups=true

# Capabilities
CapabilityBoundingSet=
AmbientCapabilities=

# System call filtering
SystemCallFilter=@system-service
SystemCallArchitectures=native

Key Directives Explained

Directive Effect
ProtectSystem=strict Read-only /usr, /boot, /etc
ProtectHome=true Inaccessible home directories
PrivateTmp=true Private /tmp namespace
NoNewPrivileges=true No privilege escalation
DynamicUser=true Automatic unprivileged user

Analyze Service Security

# Check security exposure
systemd-analyze security

# Detailed analysis of specific service
systemd-analyze security nginx.service

# Score interpretation:
# 0.0-2.0  = Excellent
# 2.0-4.0  = Good
# 4.0-6.0  = Needs improvement
# 6.0+     = Exposed

Common Service Hardening

Nginx Hardening

# /etc/systemd/system/nginx.service.d/security.conf
[Service]
ProtectSystem=full
ProtectHome=true
PrivateTmp=true
NoNewPrivileges=true
ProtectKernelTunables=true
ProtectKernelModules=true
CapabilityBoundingSet=CAP_NET_BIND_SERVICE

Database Hardening (PostgreSQL)

# /etc/systemd/system/postgresql.service.d/security.conf
[Service]
ProtectSystem=full
ProtectHome=true
PrivateTmp=true
PrivateDevices=true
NoNewPrivileges=true
ProtectKernelTunables=true
ProtectControlGroups=true
ReadWritePaths=/var/lib/postgresql /var/run/postgresql

Service Accounts

# Create service account
sudo useradd -r -s /usr/sbin/nologin -d /nonexistent myservice

# Verify no login shell
grep myservice /etc/passwd
# myservice:x:999:999::/nonexistent:/usr/sbin/nologin

# Set file ownership
sudo chown -R myservice:myservice /opt/myservice
sudo chmod 750 /opt/myservice

Resource Limits

# /etc/systemd/system/myapp.service.d/limits.conf
[Service]
# CPU limits
CPUQuota=50%

# Memory limits
MemoryMax=512M
MemoryHigh=400M

# Process limits
LimitNPROC=64
TasksMax=100

# File descriptor limits
LimitNOFILE=1024

# Prevent OOM killer from killing
OOMScoreAdjust=-500

Reload and Verify

# Reload systemd
sudo systemctl daemon-reload

# Restart service
sudo systemctl restart myapp

# Verify settings applied
systemctl show myapp --property=ProtectSystem,ProtectHome,NoNewPrivileges
intermediate System Hardening Updated 2025-01-15
  • services
  • systemd
  • hardening
  • security
  • sandboxing