Skip to content

Instantly share code, notes, and snippets.

@mike-weiner
Last active January 23, 2025 02:04
Show Gist options
  • Save mike-weiner/3e864ef8bf18d31a0e02e5e6c6d720d3 to your computer and use it in GitHub Desktop.
Save mike-weiner/3e864ef8bf18d31a0e02e5e6c6d720d3 to your computer and use it in GitHub Desktop.
An explanation of how to do basic security hardening of a Linux box.

Basic Linux Server Hardening

This document is meant to serve as a basic guide for hardening a Linux server.

Change Default Port Used by SSH

  1. sudo nano /etc/ssh/sshd_config
  2. Uncomment #Port 22 and change it to Port <SSH_PORT>. (Replace <SSH_PORT> with your desired port to use for SSH connectivity.)
  3. sudo systemctl restart ssh
  4. reboot

Enable Basic Firewall with ufw

  1. sudo ufw default deny incoming
  2. sudo ufw default allow outgoing
  3. Allow inbound traffic on specific ports:
    • sudo ufw allow <SSH_PORT>/tcp
    • sudo ufw allow 443/tcp
  4. sudo ufw enable
  5. sudo ufw status numbered
  6. sudo ufw reload

Add Non-Root sudo User to System for General Use

  1. sudo adduser --disabled-password <USERNAME>
  2. sudo usermod -aG sudo <USERNAME>

Copy Authorized SSH Keys from root to New Non-Root User

  1. mkdir -p /home/<USERNAME>/.ssh
  2. chmod 700 /home/<USERNAME>/.ssh
  3. cp ~/.ssh/authorized_keys /home/<USERNAME>/.ssh/
  4. chown <USERNAME>:<USERNAME> /home/<USERNAME>/.ssh/
  5. chown <USERNAME>:<USERNAME> /home/<USERNAME>/.ssh/authorized_keys
  6. chmod 600 /home/<USERNAME>/.ssh/authorized_keys

Allow New User to Be Passwordless Sudo

If you are using your new account for a form of automation, you may need require that it not require a password for running commands that require sudo.

  1. sudo visudo
  2. Add <USERNAME> ALL=(ALL) NOPASSWD: ALL to the bottom of the file.

Disable Non-Root & Password SSH Logins

  1. sudo nano /etc/ssh/sshd_config

    • Change PermitRootLogin yes to PermitRootLogin no.
    • Change #PubkeyAuthentication yes to PubkeyAuthentication yes.
    • Chage #PasswordAuthentication yes to PasswordAuthentication no.
    • Change #PermitEmptyPasswords no to PermitEmptyPasswords no.
    • Change #StrictModes yes to StrictModes yes.
    • Change #MaxAuthTries 6 to MaxAuthTries 3.
    • Change #MaxSessions 10 to MaxSessions 3.
  2. sudo systemctl restart ssh

  3. reboot

Add a docker User Group

If your newly created account needs to be able to run docker commands, you will want to create a docker UserGroup and adde your user to it.

  1. sudo groupadd docker
  2. sudo usermod -aG docker <USERNAME>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment