Skip to content

Instantly share code, notes, and snippets.

@ehcaning
Last active December 13, 2024 21:35
Show Gist options
  • Save ehcaning/0d5bf6b7a5e06f0c8e94adb9ac268889 to your computer and use it in GitHub Desktop.
Save ehcaning/0d5bf6b7a5e06f0c8e94adb9ac268889 to your computer and use it in GitHub Desktop.

SSH Server Hardening Steps

7 SSH Security Tips I Wish I Knew Before Getting Hacked!

1. Change Default Port

  1. Edit SSH configuration:
    vi /etc/ssh/sshd_config
    Change the Port:
    Port 2120
    
  2. Restart SSH service:
    systemctl daemon-reload
    systemctl restart ssh
  3. SSH with the new port:
    ssh -p 2120 root@SERVER_IP

2. Disable Root Login

  1. Add a new user:

    adduser ehsan
    • Use a secure password
  2. Add user to sudo group:

    usermod -aG sudo ehsan
  3. Log in with new user credentials:

    ssh -p 2120 ehsan@SERVER_IP
  4. For switching to sudo:

    sudo su
  5. Disable root login: Edit /etc/ssh/sshd_config, set:

    PermitRootLogin no
    

3. SSH Key-based Authentication

  • Copy your SSH public key to the server:
    ssh-copy-id -p 2120 ehsan@SERVER_IP

4. Disable Login with Password

  1. Edit SSH configuration:
    • Set PasswordAuthentication to no in /etc/ssh/sshd_config.
  2. Find any overrides:
    grep -i passwordauthentication /etc/ssh/sshd_config /etc/ssh/sshd_config.d/*

5. Implement 2 Factor Authentication

  1. Update package lists and install Google Authenticator:

    sudo apt update
    sudo apt-get install libpam-google-authenticator
  2. Configure Google Authenticator: Make sure to run with the user you want to use with SSH, i.e. ehsan

    google-authenticator
    • Answer prompts: y,y,n,y
  3. Edit PAM configuration:

    • In /etc/pam.d/sshd, add:
    auth required pam_google_authenticator.so nullok
    auth required pam_permit.so
    

    and Comment:

    #@include common-auth
    
  4. Edit SSH configuration for 2FA:

    vi /etc/ssh/sshd_config
    KbdInteractiveAuthentication yes
    AuthenticationMethods publickey,keyboard-interactive
    

7. IP Blocking with Fail2Ban

  1. Install Fail2ban:
    sudo apt update
    sudo apt install fail2ban
  2. Create a local Fail2ban SSH configuration:
    vi /etc/fail2ban/jail.d/sshd.local
  3. Add the following configuration:
    [sshd]
    enabled = true
    port    = 2120
    filter  = sshd
    logpath = /var/log/auth.log
    maxretry = 5
    bantime = 3600
    findtime = 600
    
  4. Restart Fail2ban service:
    systemctl restart fail2ban
  5. Check Fail2ban status for SSH:
    fail2ban-client status sshd
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment