There are 2 methods to access the SSH, one is by password based and other is key based. The SSH key based authentication is meant provide a secure way to access a server with private and public key.
In this guide you are going to learn the following ways to secure your Debian machine.
- Create new user with sudo privileges
- Disable password based auth
- Generate SSH Keys
- Configure SSH key for the user
- Disable password prompt while using sudo
Step 1: Create New User
You can skip this if you already have created the user.
Create a new user with password disabled using the following command.
sudo adduser username --disabled-password
Follow the prompts and confirm with Y
, which creates the user with the user’s home directory in /home/username
.
Grant sudo access to new user
Add the new user to the sudo group so the user will have admin privileges to run commands.
sudo usermod -aG sudo username
Now you have a new user with sudo rights and password disabled.
Step 2: Disable Password Authentication for User
Edit the /etc/ssh/sshd_config
file to configure authentication.
sudo nano /etc/ssh/sshd_config
Add the following to the last.
Match User username
PasswordAuthentication no
Save the file and restart SSH.
sudo systemctl restart ssh
Now the user cannot login using password.
Step 3: Generate SSH Key
Login as the user you have created above.
sudo su username
Create new .ssh
directory to hold the ssh keys and navigate into it.
Don’t use sudo inside here.
mkdir .ssh cd .ssh
Create SSH Keys.
ssh-keygen -m PEM -t rsa -b 4096 -C "your_email"
Here I have used to PEM
format to generate RSA based key. If the -m PEM
is removed it might generate OpenSSH key.
When prompted provide the name for the key.
Skip passphrase and complete the setup.
Now you should have 2 files inside your .ssh directory.
filename.pub filename
The filename.pub is your public key and filename is your private key.
Step 4: Configure SSH key for SSH access.
To allow SSH connection you need to add the public key to the authorized_keys
file.
cat filename.pub >> authorized_keys
This command will create a file named authorized_keys
and add the content of public key to it.
Copy the content of private key, you can make authentication to the server using this.
cat filename
This command outputs the content of your private key. Save it for auth.
Step 5: Disable Password prompt while using sudo
By default when you run sudo based commands with other user the system prompts to enter the password for the user.
As we don’t use password we need to disable it.
Exit the user shell and get back to your root shell.
Execute the command to enter visudo
.
sudo visudo
Add the following to the last.
username ALL=(ALL) NOPASSWD: ALL
Save the file and exit.
That’s it. Now you have a user who can login only using SSH keys.