Language
日本語
English

Caution

JavaScript is disabled in your browser.
This site uses JavaScript for features such as search.
For the best experience, please enable JavaScript before browsing this site.

Linux & Mac & Bash Command Dictionary

  1. Home
  2. Linux & Mac & Bash Command Dictionary
  3. Server Hardening (Initial Security Configuration)

Server Hardening (Initial Security Configuration)

"Server hardening" is the process of applying initial security settings to a newly launched server to minimize the risk of attack. It involves disabling unnecessary services, switching to SSH key authentication, enabling a firewall, and configuring automatic security updates — performed in order. Whenever you launch a server on a cloud platform or VPS, complete this checklist before deploying any applications.

Syntax

# ===============================================================
#  Server Hardening — Full Initial Setup Flow
# ===============================================================

# -----------------------------------------------
#  [1] Create a regular user
# -----------------------------------------------

# Create a regular user (e.g., webmaster) to avoid working directly as root
# useradd -m -s /bin/bash {username}
#   -m: creates the home directory
#   -s: specifies the login shell

# -----------------------------------------------
#  [2] Grant sudo privileges
# -----------------------------------------------

# Add the new user to the sudo group (Debian/Ubuntu)
# or the wheel group (RHEL/AlmaLinux)
# usermod -aG sudo {username}    # Debian/Ubuntu
# usermod -aG wheel {username}   # RHEL/AlmaLinux

# -----------------------------------------------
#  [3] Register an SSH public key
# -----------------------------------------------

# Generate a key pair on the client and copy the public key to the server
# ssh-keygen -t ed25519 -C "webmaster@example.com"   # run on the client
# ssh-copy-id {username}@{server-ip}              # copy the public key to the server

# -----------------------------------------------
#  [4] Harden SSH settings (/etc/ssh/sshd_config)
# -----------------------------------------------

# Change the following settings to disable password auth and root login
# Port 22022                    # Change from the default port (22) — optional
# PermitRootLogin no            # Disallow direct root login
# PasswordAuthentication no     # Disable password authentication
# PubkeyAuthentication yes      # Enable public key authentication
# AllowUsers webmaster deploy    # Restrict login to specific users

# -----------------------------------------------
#  [5] Enable the firewall
# -----------------------------------------------

# Enable UFW (Debian/Ubuntu) or firewalld (RHEL)
# The order matters: allow the SSH port before enabling the firewall
# ufw allow 22022/tcp   # Allow the new SSH port first
# ufw enable            # Enable the firewall

# -----------------------------------------------
#  [6] Disable unnecessary services
# -----------------------------------------------

# Prevent unused services from running
# systemctl disable --now {service-name}
#   e.g.: sudo systemctl disable --now cups        # printing service (if not needed)
#   e.g.: sudo systemctl disable --now avahi-daemon

# -----------------------------------------------
#  [7] Configure automatic security updates
# -----------------------------------------------

# Automatically apply security patches
# apt install unattended-upgrades   # Debian/Ubuntu
# dpkg-reconfigure --priority=low unattended-upgrades

Settings Overview

SettingDescription
Create a regular userCreate a dedicated user to avoid using root for day-to-day tasks. Use useradd -m -s /bin/bash {username} to create the user with a home directory and shell.
Add to sudo / wheel groupDelegate administrative privileges to the new user. On Ubuntu-based systems, add the user to the sudo group; on RHEL-based systems, use the wheel group.
Configure SSH key authenticationUse public key authentication, which is more secure than password authentication. Generate a key pair with ssh-keygen and transfer the public key to the server with ssh-copy-id.
PasswordAuthentication noDisables password authentication in /etc/ssh/sshd_config. Verify that key authentication works before applying this setting. Restart sshd after making the change.
PermitRootLogin noDisallows direct SSH login to the root account. Root operations should only be performed through sudo.
Change the SSH portChanging from the default port 22 reduces automated brute-force attempts. After changing the port, open it in the firewall before restarting sshd.
Restrict users with AllowUsersExplicitly lists the users permitted to log in via SSH. Any user not in the list will be denied access.
Enable the firewallEnable UFW (Ubuntu-based) or firewalld (RHEL-based) and open only the ports you need. Always allow the SSH port before enabling the firewall.
Disable unnecessary servicesUse systemctl disable --now to stop unnecessary services and prevent them from starting automatically. This minimizes the attack surface.
Install fail2banDetects brute-force attacks against SSH and automatically bans IP addresses that exceed a failure threshold. Install with apt install fail2ban.
Automatic security updatesunattended-upgrades (Ubuntu-based) automatically applies security patches. Kernel updates and other major changes are generally handled manually.
Remove unnecessary packagesRemove unused packages with apt purge or dnf remove to reduce the number of potential vulnerabilities.

Examples

Initial security setup script for a new server
# ===============================================================
#  New Ubuntu Server Hardening Procedure (Full)
#  Example: setting up a VPS where webmaster logs in
# ===============================================================

# -----------------------------------------------
#  [1] After logging in as root, update all packages first
# -----------------------------------------------

apt update && apt full-upgrade -y

# -----------------------------------------------
#  [2] Create user "webmaster" and grant sudo privileges
# -----------------------------------------------

# Create the user (-m: create home directory, -s: specify shell)
useradd -m -s /bin/bash webmaster

# Set a password (used temporarily before key authentication is set up)
passwd webmaster

# Add to the sudo group
usermod -aG sudo webmaster

# -----------------------------------------------
#  [3] Generate an SSH key pair on your client PC
#      NOTE: Run these commands on the client, not the server
# -----------------------------------------------

# Generate a key in ed25519 format (more secure and shorter than RSA)
# ssh-keygen -t ed25519 -C "webmaster@example.com"

# Transfer the public key to the webmaster user on the server
# ssh-copy-id -i ~/.ssh/id_ed25519.pub webmaster@<server-ip>

# -----------------------------------------------
#  [4] Verify you can log in as webmaster before changing SSH settings
#      NOTE: From this point, use sudo as the webmaster user
# -----------------------------------------------

# Back up sshd_config before editing
sudo cp /etc/ssh/sshd_config /etc/ssh/sshd_config.bak
sudo nano /etc/ssh/sshd_config

# --- Settings to apply in sshd_config ---
# Port 22022               # Change the port (optional)
# PermitRootLogin no       # Disable root login
# PasswordAuthentication no
# PubkeyAuthentication yes
# AllowUsers webmaster deploy   # Explicitly list allowed users
# ----------------------------------------

# Check the config syntax, then restart sshd
sudo sshd -t && sudo systemctl restart sshd

# -----------------------------------------------
#  [5] Configure the UFW firewall
# -----------------------------------------------

# Allow the new SSH port first (forgetting this will lock you out)
sudo ufw allow 22022/tcp comment 'SSH'

# If running a web server, also open HTTP/HTTPS
sudo ufw allow 80/tcp comment 'HTTP'
sudo ufw allow 443/tcp comment 'HTTPS'

# Set default policies (deny incoming, allow outgoing)
sudo ufw default deny incoming
sudo ufw default allow outgoing

# Enable the firewall
sudo ufw enable

# Verify the rules
sudo ufw status numbered

# -----------------------------------------------
#  [6] Disable unnecessary services
# -----------------------------------------------

# Printing service (not needed on a web server)
sudo systemctl disable --now cups 2>/dev/null || true

# Avahi daemon (mDNS — not needed outside a local LAN)
sudo systemctl disable --now avahi-daemon 2>/dev/null || true

# -----------------------------------------------
#  [7] Install fail2ban to protect SSH from brute-force attacks
# -----------------------------------------------

sudo apt install -y fail2ban

# Create jail.local to override the SSH settings
sudo tee /etc/fail2ban/jail.local <<'EOF'
[sshd]
enabled = true
port = 22022
maxretry = 5
bantime = 3600
findtime = 600
EOF

sudo systemctl enable --now fail2ban

# -----------------------------------------------
#  [8] Configure automatic security updates
# -----------------------------------------------

sudo apt install -y unattended-upgrades

# Enable automatic updates interactively (select "Yes")
sudo dpkg-reconfigure --priority=low unattended-upgrades

# Verify the configuration
cat /etc/apt/apt.conf.d/20auto-upgrades

Run the following command:

$ sudo ufw status numbered
Status: active

     To                         Action      From
     --                         ------      ----
[ 1] 22022/tcp                  ALLOW IN    Anywhere                   # SSH
[ 2] 80/tcp                     ALLOW IN    Anywhere                   # HTTP
[ 3] 443/tcp                    ALLOW IN    Anywhere                   # HTTPS
[ 4] 22022/tcp (v6)             ALLOW IN    Anywhere (v6)              # SSH
[ 5] 80/tcp (v6)                ALLOW IN    Anywhere (v6)              # HTTP
[ 6] 443/tcp (v6)               ALLOW IN    Anywhere (v6)              # HTTPS

$ sudo fail2ban-client status sshd
Status for the jail: sshd
|- Filter
|  |- Currently failed:	2
|  |- Total failed:	47
|  `- File list:	/var/log/auth.log
`- Actions
   |- Currently banned:	1
   |- Total banned:	3
   `- Banned IP list:	203.0.113.42

$ cat /etc/apt/apt.conf.d/20auto-upgrades
APT::Periodic::Update-Package-Lists "1";
APT::Periodic::Unattended-Upgrade "1";

Overview

"Server hardening" is a series of initial configuration steps designed to reduce the chance of a successful attack. The three highest-priority steps are: creating a regular user with sudo privileges, switching to SSH key authentication, and disabling password authentication. For details on SSH configuration options (port, AllowUsers, connection timeouts, etc.), see the sshd_config page. For managing firewall rules, see the ufw page. Automatic banning of brute-force SSH attacks is covered in detail on the fail2ban page. Two rules are essential to avoid locking yourself out: always allow the SSH port before enabling the firewall, and always confirm that key authentication works before disabling password authentication.

If you find any errors or copyright issues, please .