SSH public key authentication: Difference between revisions

From NixOS Wiki
imported>Sashanoraa
imported>Brogolem35
No edit summary
Line 37: Line 37:
   enable = true;
   enable = true;
   # require public key authentication for better security
   # require public key authentication for better security
   passwordAuthentication = false;
   settings.PasswordAuthentication = false;
   kbdInteractiveAuthentication = false;
   settings.KbdInteractiveAuthentication = false;
   #permitRootLogin = "yes";
   #settings.PermitRootLogin = "yes";
};
};
</syntaxhighlight>
</syntaxhighlight>

Revision as of 16:39, 15 July 2023

To setup a public key based SSH connection from clientmachine to servermachine:

[user@clientmachine] $ ssh-keygen -f ~/.ssh/servermachine
[user@clientmachine] $ ssh-copy-id -i ~/.ssh/servermachine servermachine

Now the public key is stored on the servermachine in /home/user/.ssh/authorized_keys

On the clientmachine, we stored the key file in the non-standard path ~/.ssh/servermachine, so we must tell the SSH client to use the key file:

[user@clientmachine] $ ssh -i ~/.ssh/servermachine servermachine

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 servermachine
  HostName 192.168.1.105
  #Port 22
  #User user

  # Prevent using ssh-agent or another keyfile, useful for testing
  IdentitiesOnly yes
  IdentityFile ~/.ssh/servermachine

SSH server config

Optionally, on the NixOS-based servermachine, 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@clientmachine after the public key
  # but we can remove the "@clientmachine" part
];

... or use a custom path for the authorized_keys file:

users.users."user".openssh.authorizedKeys.keyFiles = [
  /etc/nixos/ssh/authorized_keys
];

See also