Blog | G5 Cyber Security

Secure File Access with SSH Keys

TL;DR

This guide shows you how to use SSH keys for secure file access instead of passwords. It’s more secure and easier in the long run.

What are SSH Keys?

SSH (Secure Shell) keys let you log into a server or access files without typing your password every time. They work with a pair of keys: a private key (keep this secret!) and a public key (you share this).

Step 1: Generate an SSH Key Pair

  1. Open your terminal. This is where you’ll type commands.
  2. Run the following command:
    ssh-keygen -t rsa -b 4096

    This creates a new RSA key pair with a strong 4096-bit length.

  3. Follow the prompts:
    • Enter file in which to save the key (/home/your_user/.ssh/id_rsa): Press Enter to accept the default location (recommended).
    • Enter passphrase (empty for no passphrase): It’s highly recommended to set a strong passphrase. This adds an extra layer of security even if your private key is stolen. Type it in and press Enter twice to confirm.

This will create two files in the ~/.ssh/ directory:

Step 2: Copy your Public Key to the Server

There are several ways to do this. We’ll use ssh-copy-id, which is the easiest if it’s available.

  1. Use ssh-copy-id:
    ssh-copy-id user@server_address

    Replace user with your username on the server and server_address with the server’s IP address or hostname. You’ll be prompted for your password one last time.

  2. If ssh-copy-id isn’t available:
    • Display your public key:
      cat ~/.ssh/id_rsa.pub
    • Copy the entire output of this command.
    • Log into the server using your password.
    • Edit the ~/.ssh/authorized_keys file: If it doesn’t exist, create it.
      nano ~/.ssh/authorized_keys
    • Paste your public key into this file. Make sure it’s on a single line and there are no extra spaces or characters.
    • Save the file and exit the editor.

Step 3: Test your SSH Key Login

  1. Open a new terminal window.
  2. Try to log into the server:
    ssh user@server_address

    Replace user and server_address as before.

  3. If you set a passphrase, you’ll be prompted for it. If everything is configured correctly, you should log in without being asked for your password!

Step 4: Disable Password Authentication (Optional but Recommended)

To further improve security, disable password authentication on the server.

  1. Log into the server using SSH keys.
  2. Edit the SSH configuration file:
    sudo nano /etc/ssh/sshd_config
  3. Find these lines and change them as follows:
    • PasswordAuthentication no
    • ChallengeResponseAuthentication no (if present, set to ‘no’)
  4. Save the file and exit the editor.
  5. Restart the SSH service:
    sudo systemctl restart sshd

Warning: Make sure you can log in with SSH keys before disabling password authentication. Otherwise, you might lock yourself out of your server!

Exit mobile version