SSH public key authentication

From NixOS Wiki
Revision as of 11:32, 24 October 2021 by Milahu (talk | contribs) (Created page with "Let's assume a <code>servermachine</code> is running NixOS. To setup a public key based SSH connection from <code>clientmachine</code> to <code>servermachine</code>: <syntaxh...")
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to: navigation, search

Let's assume a servermachine is running NixOS. 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

Note: On the clientmachine, we created the public key file in the non-standard path ~/.ssh/servermachine, so later we must use ssh -i ~/.ssh/servermachine servermachine to send our public key.

Now, on the servermachine, we must tell the SSH server, where to find the authorized_keys file. To /etc/nixos/configuration.nix we add:

services.openssh = {
  enable = true;
  authorizedKeysFiles = [ ".ssh/authorized_keys" ];
#  passwordAuthentication = false; 
#  permitRootLogin = "yes";
#  challengeResponseAuthentication = false;
};

Optionally, we can set passwordAuthentication = false; to require public key authentication, usually for better security.

Now we must tell the SSH client to send the public key:

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

The connection should work without password.

Alternative config

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
];