How can I copy an SSH key into ~/.ssh?

I want to copy it like this:


 18   home-manager.users.root = {
 19     home.stateVersion = "23.11";
 20
 21     #copy key for Bytesized
 22     home.file.".ssh/id_root_quasar".source = "${self}/id_root_quasar";
 23   };

This doesn’t work, cause the permissions are not tolerated;)

I’m reading this bug, but I’m not really sure if they suggest a workaround?

are you sure you want to do this? private ssh keys should not be world-readable, but including them in your config this way will expose them to every user on the machine in the nix store.

Beware that, with that construction, your SSH key is in the Nix store, and is thus readable by all users on the system. Don’t do that (you will have to remove the unencrypted secret from your repo entirely as flakes copy the entire repo to the store by default). You may wish to rotate your key as well.

Instead, use agenix, sops-nix, or some other means of safely storing secrets in the Nix store. This will also solve the mode problem, as both these allow for setting the mode on the created file.

2 Likes

The key may be protected by a passphrase, so the above comments (while valid) are potentially mitigated. Still not ideal practice, because the passphrase could be brute-forced.

But probably not: root’s keys are often intended for unattended use, without a passphrase. Use cases like sending backups to another host are common.

So, yes, in general, protecting secrets from disclosure via the store and repo should be done using tools like agenix, sops-nix, etc.

For the case of keys like this, though, I feel it’s better to not manage the private key via nix at all. Host and root private keys are secret state, generated on the machine itself and kept there (and maybe backed up along with other state, securely). Every machine has their own. Instead, what you manage with nix is where the public key is trusted and accepted: for logins to the backup server, in known hosts files for the community of hosts, and so on.

That’s not always possible, of course: some of those places may not be under nix’s control. But where you can, this is the much better pattern. And it’s the pattern that tools like agenix implicitly rely on, when they use the ssh host key as the standard key protecting those secrets that can’t work this way for deployment to that host.