Creating a key to have access to your server through ssh is the safest way to get access to your server.

In your client machine just type:

ssh-keygen -t rsa-sha2-512 -b 4096 -C "[email protected]"

Or, for an elliptic curve signing algorithm alternative:

ssh-keygen -t ed25519 -C "[email protected]"

It is going to ask you the location, just hit “Enter”, and if you want a password just type, confirm, and the key is created.

When needed to change the password of the private key issue:

ssh-keygen -p -f ~/.ssh/id_dsa

Or simply:

ssh-keygen -p

For manually extract the public key from the private:

ssh-keygen -y -f ~/.ssh/id_rsa > ~/.ssh/id_rsa.pub

The whole directory must be protected from being read by other users:

chmod 700 -R ~/.ssh

To transfer your key to the server issue the command:

ssh-copy-id [email protected]

Confirm the password that you used to type to log in to your server.

The public key can be manually installed by appending the id_rsa.pub into the authorized_keys.

cat ~/.ssh/id_rsa.pub >> ~/.ssh/authorized_keys

To check the algorithm type of an existent key:

ssh-keygen -l -f ~/.ssh/id_rsa

Done! Now just try to connect again.

ssh domain.com

If you did everything correctly you are already logged in.

It is always a good idea to have another account set just in case you type something wrong and lock yourself out. If this is the case, log in with the second account, switch to your user, or root, and delete the files inside the folder ~/.ssh/.

As a good practice, always protect your SSH as much as you can. See the recommendations below:

sudo nano /etc/ssh/sshd_config

Configuration parameters you should pay attention to:

AllowUsers user
PermitRootLogin no
PubkeyAuthentication yes
PasswordAuthentication no
PermitEmptyPasswords no

Replace “user” with your own user id. Restart your server:

sudo systemctl restart sshd.service

BONUS

If you need to hop on a server that is the entry point of a network to reach one internal server use the ProxyJump functionality:

ssh -J [email protected] [email protected]

Or create a configuration to automate this process:

nano ~/.ssh/config

With the following configuration customized accordingly:

Host external
    HostName 200.200.200.200
    User user1
Host internal
    HostName 10.0.0.1
    User user2
    IdentityFile ~/.ssh/id_rsa
    ProxyJump external

Many other parameters can be configured in this file:

Host serverA
    HostName 192.168.0.1
    User user3
    Port 2222
    Protocol 2
    IdentityFile ~/.ssh/serverA.key
    LogLevel INFO
    Compression yes
    ServerAliveInterval 60
    ServerAliveCountMax 30
    ForwardAgent no
    ForwardX11 no
    ForwardX11Trusted yes
    ProxyJump [email protected]:22,[email protected]:2222

Host * !192.168.0.1
    User ubuntu

Or to bypass any pre-configuration and only give the arguments of the command:

ssh -F /dev/null user@host

Discover new functionalities over SSH on the post Reverse Shell with AutoSSH [Link]