SSH using private key
My server was hacked and had some malwares, crypto miners. I was too dumb to open port to ssh server from home. After 2 days, I've clean my Ubuntu server 20.04 and want to secure my server. I decided to use tailscale that I can ssh to my server and in order to harden Hackers, I used private key to ssh. By using an SSH Key, I'm replacing a guessable password with a cryptographic file that only I possess.
Here is how
Here is the step-by-step guide to generating the key on my MacBook, installing it on Ubuntu, and backing it up so I don't lose access.
Phase 1: Generate the Key (Do this on my MacBook)
Open the Terminal app on MacBook (
Cmd+Space, type "Terminal").Run this command to generate a modern, secure key (Ed25519):
ssh-keygen -t ed25519 -C "macbook-key"The Prompts:
Enter file in which to save the key: Just press Enter (defaults to
/Users/mymacbookUserName/.ssh/id_ed25519).Enter passphrase: Press Enter for no password, or type a password for extra security. (Recommend pressing Enter for now to keep it simple).

Phase 2: Copy the "Lock" to Ubuntu
Now need to send the Public Key (the lock) to the Ubuntu server.
Stay in MacBook terminal.
Run command (replace
100.x.y.zwith Ubuntu's Tailscale IP):(Note: Use actual ubuntuUsername).
It will ask for Ubuntu user's password one last time. Enter it.
What just happened? The MacBook took its public key and wrote it into a file called ~/.ssh/authorized_keys on Ubuntu machine. The MacBook is now "Authorized."

Phase 3: Verify access (CRITICAL)
Before disabling passwords, we MUST prove the key works.
From MacBook, try to log in:
Did it ask for a password?
NO: It logged straight in? Great! Proceed to Phase 4.
YES: Something went wrong. DO NOT disable password login yet, or you will lock yourself out.
Phase 4: Disable Password Login (On Ubuntu)
Now that you confirmed you can get in without a password let's disable logging in with password
On the Ubuntu machine (via SSH connection):
Set these lines:
Plaintext
Save (
Ctrl+O,Enter) and Exit (Ctrl+X).Restart SSH:
Bash
Phase 5: Keep key forever (The "Backup" Strategy)
You asked: "How to keep my sshkey that even after I change my machine I still can ssh into it"
Your SSH identity consists of two files located in the hidden ~/.ssh/ folder on your MacBook.
id_ed25519(The Private Key): This is the secret. This is your "Ticket."id_ed25519.pub(The Public Key): This is what you put on servers.
To move to a NEW computer (e.g., a new MacBook) without losing access:
On your OLD MacBook: Copy the
id_ed25519file to a secure USB drive or encrypted cloud storage.Bash
On your NEW MacBook: Create the
.sshfolder and paste the key back in.Bash
Set Permissions (Vital): SSH will refuse to use the key if the permissions are too open. Run this on the new Mac:
Bash
Summary: As long as you possess that id_ed25519 file, you can log into your Ubuntu server from any computer in the world. Guard it with your life.
Last updated