SSH public key authentication: Difference between revisions
imported>Almino m Just to make things easier to understand |
imported>Almino Telling people how to use a different port |
||
Line 4: | Line 4: | ||
[user@your-machine] $ ssh-keygen -f ~/.ssh/another-machine | [user@your-machine] $ ssh-keygen -f ~/.ssh/another-machine | ||
[user@your-machine] $ ssh-copy-id -i ~/.ssh/another-machine another-machine-host-or-ip | [user@your-machine] $ ssh-copy-id -i ~/.ssh/another-machine another-machine-host-or-ip | ||
</syntaxhighlight> | |||
In case <code>another-machine</code> uses another port for SSH connections use this command instead: | |||
<syntaxhighlight lang="console"> | |||
[user@your-machine] $ ssh-copy-id -i ~/.ssh/another-machine -p1234 another-machine-host-or-ip | |||
</syntaxhighlight> | </syntaxhighlight> | ||
Revision as of 19:21, 24 October 2023
To setup a public key based SSH connection from your-machine
(client) to another-machine
(server):
[user@your-machine] $ ssh-keygen -f ~/.ssh/another-machine
[user@your-machine] $ ssh-copy-id -i ~/.ssh/another-machine another-machine-host-or-ip
In case another-machine
uses another port for SSH connections use this command instead:
[user@your-machine] $ ssh-copy-id -i ~/.ssh/another-machine -p1234 another-machine-host-or-ip
Now the public key is stored on the another-machine
in /home/user/.ssh/authorized_keys
On your-machine
, we stored the key file in the non-standard path ~/.ssh/another-machine
, so we must tell the SSH client to use the key file:
[user@clientmachine] $ ssh -i ~/.ssh/another-machine another-machine-host-or-ip
The connection should work without password.
To make the SSH client automatically use the key file, we add this to /home/user/.ssh/config
:
Host another-machine
HostName 192.168.1.105 # another-machine-host-or-ip
#Port 22
#User user
# Prevent using ssh-agent or another keyfile, useful for testing
IdentitiesOnly yes
IdentityFile ~/.ssh/another-machine
SSH server config
Optionally, on the NixOS-based another-machine
, we can set passwordAuthentication = false;
to require public key authentication for better security.
services.openssh = {
enable = true;
# require public key authentication for better security
settings.PasswordAuthentication = false;
settings.KbdInteractiveAuthentication = false;
#settings.PermitRootLogin = "yes";
};
We can also store the public keys in /etc/nixos/configuration.nix
:
users.users."user".openssh.authorizedKeys.keys = [
"ssh-rsa AAAAB3Nz....6OWM= user" # content of authorized_keys file
# note: ssh-copy-id will add user@your-machine after the public key
# but we can remove the "@your-machine" part
];
... or use a custom path for the authorized_keys
file:
users.users."user".openssh.authorizedKeys.keyFiles = [
/etc/nixos/ssh/authorized_keys
];