{
  "id": "ssh-keys",
  "title": "SSH Key Authentication",
  "category": "access",
  "tags": ["ssh", "authorized_keys", "keys", "permissions"],
  "updated": "2025-11-03",
  "summary": "How SSH key auth works and how to set it up correctly.",
  "sections": [
    {
      "heading": "How It Works",
      "body": "<p>SSH key authentication replaces passwords with a cryptographic key pair. The <strong>private key</strong> stays on your machine. The <strong>public key</strong> goes into <code>~/.ssh/authorized_keys</code> on the target host. When you connect, the server checks whether your private key corresponds to one of the public keys it trusts.</p><p>There is no password transmitted. Either the key matches or the connection fails.</p>"
    },
    {
      "heading": "Generating a Key Pair",
      "body": "<p>Use <code>ed25519</code> unless something forces you onto RSA. It is smaller and more secure.</p>",
      "code": "ssh-keygen -t ed25519 -C \"your-comment-here\"\n# Accept the default path (~/.ssh/id_ed25519) or specify one.\n# Passphrase is optional but recommended for keys that leave your machine."
    },
    {
      "heading": "Installing the Public Key",
      "body": "<p>Copy the public key to the remote host:</p>",
      "code": "# Option 1 — if password auth is still working\nssh-copy-id -i ~/.ssh/id_ed25519.pub user@host\n\n# Option 2 — manually\ncat ~/.ssh/id_ed25519.pub >> ~/.ssh/authorized_keys"
    },
    {
      "heading": "File and Directory Permissions",
      "body": "<p>This is the most common reason key auth fails. SSH will silently reject keys if the permissions are too open.</p>",
      "code": "chmod 700 ~/.ssh\nchmod 600 ~/.ssh/authorized_keys\nchown -R youruser:youruser ~/.ssh"
    },
    {
      "heading": "Troubleshooting",
      "body": "<p>Run <code>ssh -v user@host</code> for verbose output. The auth failure reason is usually in the first 20 lines.</p><p>Common causes:</p><ul><li><code>authorized_keys</code> file has wrong permissions (see above)</li><li><code>~/.ssh</code> directory is world-writable</li><li><code>authorized_keys</code> file does not exist</li><li>The file exists but is empty or the key was pasted with a line break in the middle</li><li><code>sshd_config</code> has <code>PubkeyAuthentication no</code></li></ul>"
    },
    {
      "heading": "Checking the sshd Config",
      "body": "<p>Relevant lines in <code>/etc/ssh/sshd_config</code>:</p>",
      "code": "PubkeyAuthentication yes\nAuthorizedKeysFile .ssh/authorized_keys\n\n# After editing sshd_config, test before reloading:\nsshd -t\nsystemctl reload ssh"
    }
  ]
}
