Setup SSH server using public key authentication
Before setting up a SSH server at home for access from outside, such as from our mobile phones, we need to apply a dynamic public IP from the ISP. Because the server is usually hidden from the public network by NAT (Network address translation), we should create a set of port mapping rules in the optical modem and/or WIFI router(s) until reaching our SSH server port.
To prevent malicious brute-force password breaking, use public key authentication is safer than the traditional password authentication. The procedures are as follows.
-
Edit SSH server configuration file
/etc/ssh/sshd_config
with the following modifications:Port <port> PermitRootLogin no PubkeyAuthentication yes PasswordAuthentication no ClientAliveInterval 300 X11Forwarding no AllowUsers <system-user-name>
-
Restart SSH server
sudo /etc/init.d/ssh restart
-
Create a pair of keys on the client. N.B.
ed25519
is safer and efficient than RSA encryption. If the client runs Linux, simply execute thessh-keygen
command:ssh-keygen -t ed25519
After running this command, a file
id_ed25519.pub
will be generated.Since I will also control my Linux server via Shortcut SSH commands on iOS, the above keys can be automatically generated by iOS if I select the authentication method as “SSH key”.
- Send the
id_ed25519.pub
file generated byssh-keygen
or copy the public key generated by iOS to the server. -
Add the public key from the client to
~/.ssh/authorized_keys
on the server.touch ~/.ssh/authorized_keys cat id_ed25519.pub >> ~/.ssh/authorized_keys rm id_ed25519.pub
Up to now, the configuration for public key authentication is complete. We can login to the server as below:
ssh -p <port> -l <username> <ip>
Or we can directly use scp
to transfer files between the server and the client:
scp [-r] -P <port> <local-path> <username>@<server-ip>:<remote-path>