Introduction

SSH (Secure Shell) in a network protocol used for communication securely between two devices. it is primarily used to connect to remote machines, such as servers and workstations, from various client devices, including laptops, and mobile phones. For the authentication SSH offers several methods: passwords (which are less secure), public key authentication (more secure), and other less common techniques like two-factor authentication.

To use SSH protocol with public key authentication, you typically follow three stages: 1.Generate a key-pair 2.Install the public key on the server 3.Connect without a password

Setup Public Key Authentication

Generate a Key Pair

There are several key types to consider: RSA (more compatible but less secure) and ED25519 (modern and more secure). To generate a key pair, use the command ssh-keygen specifying the key type with -t flag.

RSA

# Basic RSA key generation (more compatible but less secure)
ssh-keygen -t rsa -f ~/.ssh/key_name -C 'a commant'

# Generate a larger RSA key (slower connection)
ssh-keygen -t rsa -b 4096 -f ~/.ssh/key_name -C 'a commant'

ED25519

# Basic ED25519 key generation
ssh-keygen -t ed25519 -f ~/.ssh/key_name -C "a commant"

# ED25519 key generation with higher KDF (Key Derivation Function) rounds
ssh-keygen -t ed25519 -a 16 -f ~/.ssh/key_name -C "a commant"

This process will generate two keys: a public (key_name.pub) and private (key_name). Keep the private key on your machine (the client) and install the public key on the server.

Install the Public Key on the Server

Automated using ssh-copy-id

If you have access via a password, you can use the following command on your local machine:

ssh-copy-id username@server-ip

Manually

  1. Display the public key: cat ~/.ssh/key_name.pub
  2. Copy the public key content.
  3. Add it in the ~/.ssh/authorized_keys file on target system.

[!NOTE] File Permissions SSH is extremely strict about permissions and will refuse to work if these files are too accessible to other users. Set the permission as follows:

# Full permissions for the owner, no permissions for others
chmod 700 ~/.ssh
# Read/Write permissions for the owner, no permissions for others
chmod 600 ~/.ssh/authorized_keys

Connect Without a Password

To connect without a password, use ssh command from your machine:

ssh username@server-ip

We can also simplifies SSH connection by creating aliases and setting default options for different hosts, in a ~/.ssh/config file. This powerful configuration file can look like the following:

Host server
    HostName 192.168.1.54
    User john
    Port 2222
    IdentityFile ~/.ssh/key_name

# For identification only (e.g., GitHub)
Host alias_here
    HostName github.com
    IdentityFile ~/.ssh/key_name_github
    IdentitiesOnly yes