Secure Shell (ssh) Protocol
Feb 11, 2023OpenSSH
is a tool for connecting remote
using ssh
protocol.
Install OpenSSH
using your native package manager.
Connect
ssh -p 22 user@remote
-p
tag is the default port that ssh using. user
is your remote username (e.g sanatan
) and remote is the ip address of the remote(e.g 192.168.0.1
). Accept the fingerprint by typing yes
and provide your password to connect the remote. All the remote's public key is stored in ~/.ssh/known_hosts
file.
Generate key
ssh-keygen -t rsa -b 4096
Give a name ~/.ssh/sanatan_rsa
and chose a passphrase or leave it blank. The following command will generate private key sanatan_rsa
and public key sanatan_rsa.pub
in the ~/.ssh
directory.
Share public key
Create a file ~/.ssh/authorized_keys
in the remote server and manually paste the public key (for our case sanatan_rsa.pub
) or you can use
ssh-copy-id sanatan@remote
# or
cat sanatan_rsa.pub|ssh sanatan@192.68.0.1 -T 'cat>>~/.ssh/authorized_keys'
Now you can connect the remote
ssh -p 22 -i ~/.ssh/sanatan_rsa sanatan@192.168.0.1
This time it will not ask to enter password and you will be connected to remote automatically.
Configure
Configure your local ssh
configuration file for
Host myhost
HostName 192.168.0.1
User sanatan
IdentityFile ~/.ssh/sanatan_rsa
Port 22
Now you can connect by
ssh myhost
Protect remote
First set permission for authorized_keys
file on the remote server
chmod 400 ~/.ssh/authorized_keys
Edit the configuration file
sudo nano /etc/ssh/sshd_config
and disable root login and password authetication
PermitRootLogin no
PasswordAuthentication no
you can also change the port
that ssh listen into
Port 4422
restart
the service
sudo systemctl restart sshd
Two-factor
You can additionally set two factor authention to remotely login to the server
sudo apt install libpam-google-authenticator
google-authenticator
scan the QR
code into your authenticator app
(e.g google authenticator)
Edit ssh
for pam
module
sudo vim /etc/pam.d/sshd
and add these two lines at the bottom
auth required pam_google_authenticator.so
auth required pam_permit.so
and comment out
#@include common-auth
Now edit system ssh
configuration file
sudo nano /etc/ssh/sshd_config
and do neccessary changes
# ChallengeResponseAuthentication no
ChallengeResponseAuthentication yes
and add
AuthenticationMethods publickey,keyboard-interactive
Finally restart the sshd.service
sudo systemctl restart sshd.service
Firewall
sudo ufw allow OpenSSH
# or
sudo ufw allow from 192.168.0.0/24
sudo ufw enable
sudo ufw status
Additionally, you can use fail2ban
for not allowing brute-forcing
on the remote server.
Happy ssh :)