We are still actively working on the spam issue.

Difference between revisions of "Home server/Remote access"

From InstallGentoo Wiki
Jump to: navigation, search
(Created page with "=Security= Unlike a desktop, a server is always working, accepts connections from the internet (your desktop is normally firewalled and doesn't have any ports open) and is eas...")
 
m (Troubleshooting)
 
(21 intermediate revisions by 4 users not shown)
Line 1: Line 1:
=Security=
+
SSH stands for Secure Shell and is a protocol for secure remote login and other secure network services over an insecure network, which basically means you can access your server from your computer over a network and execute commands as if you were typing them on the server itself. OpenSSH, the most popular SSH software, comes with a client and a server, the config files are <code>/etc/ssh/ssh_config</code> and <code>/etc/ssh/sshd_config</code> respectively. An OpenSSH server can also act as a file server using the sftp client. SFTP enables you to <code>put</code> and <code>get</code> files on and off your server, as well as many other things.
Unlike a desktop, a server is always working, accepts connections from the internet (your desktop is normally firewalled and doesn't have any ports open) and is easy to discover (especially if you send mail from it). It's under a bit more risk, and its worth thinking about what intrusions you will try to prevent and how.
 
  
== Threat model==
+
=Setup=
There are 4 main classes of attackers, grouped by what sorts of security measures are appropriate for them.
+
You usually enable the ssh server during the installation. Do this if possible, it is the simplest way.
  
===Busybodies===
+
* If you did not setup ssh to auto start on boot, using systemd type:
These are extremely unmotivated people like asshole flatmates or nosy neighbors (who end up on your WAN). They will rarely even try anything, and if they do, they will make the tiniest of efforts and give up at the first sign of difficulty.
+
sudo systemctl enable ssh && sudo systemctl start ssh
 +
* If that does not work, you need to install OpenSSH with your package manager
 +
sudo apt install openssh-server
  
Just put good passwords on your shit and don't tell them to anyone, and it will be enough for this group.
+
=SSH keyfile authentication=
 +
We are going to use ssh & ssh-keygen in this tutorial because its consistently available on almost all platforms, including GNU/Linux, BSD, and OSX (by default), and Windows (You're not going to use wangblows and also worry about NSA backdoors are you?).  You can also use PuTTY if you need a GUI crutch or something else entirely, but if you were a tard like that, you probably shouldn't use this page, amirite?
  
===Casual snoopers===
+
First make the ssh directory for your client:
These are attackers who actually have a strong motive to get your data, but aren't competent and don't have the resources to make a serious attack. Say a burglar steals your computer. Of course he will try turning it on and seeing if there's anything interesting inside. He will not hesitate at all, unlike the previous group. Hopefully, he will see a password prompt, and after a few tries, give up on trying to guess it. However, again unlike the previous group, he will not stop there. If at all computer literate, he will try to plug the hard drive into another computer, or boot from a LiveCD. At that point it's possible that you will be the victim of identity theft.
 
  
Technically, this group has physical access, so by the common maxim of computer security, you have already lost. But in practice, they could only defeat your security theoretically. In practice, they don't know how to actually leverage that physical access, and probably won't bother trying.
+
mkdir ~/.ssh
  
Full disk encryption will deter this group, since they don't have the resources to defeat, and will simply give up and just sell the hardware at that point. Encryption takes a lot of work to defeat, and most of the shit people encrypt honestly isn't valuable or worth bothering with.
+
OpenSSH includes a program called ssh-keygen. To generate a public/private key pair run:
  
===Skids===
+
ssh-keygen -a 256 -t ed25519
Within even the first day of your server's uptime, you will realize that there's tons people constantly trying to hack your machine. There is a sliding scale: There are tons of shitty script kiddies just randomly scanning ports over a range of IPs, and when they see your server responding, they start trying to bruteforce the SSH. This is extremely common and very easy to protect against. On the other hand, there are some extremely determined, very skilled hackers who buy 0days on the black market and use them, but these will probably be rarer, and they will prefer go after juicier targets like banks before coming after your home server full of animu porn.
 
  
The way to defend against this group is to configure your server for strong security, always keep your software up to date as new exploits appear, and keep a close eye on signs of intrusion. Defending against this group is probably the bulk of your security related maintenance workload.
+
* With ed25519 the default bitsize is plenty secure (the -b flag is ignored for ed25519 anyways) - nobody's gonna crack that shit easily, the [[NSA]] infiltrated the RSA, and DSA is old and insecure, so fuck that. 
 +
* Optionally enter a strong password when prompted, this is not meant to authenticate you against the SSH server, but to keep the private key secure in case it's stolen from your client machine.  
  
At the same time, you have to recognize that you the only way to have perfect security is to turn off your server and disconnect it from the internet. Consider something like the Heartbleed bug: There is nothing you could have done to protect against it, even if you acted the moment the news broke (you could have been attacked before the news were out). That said, if a bad guy got hold of Heartbleed, he probably wouldn't attack you (there are much better targets), and just because you can't have perfect security, doesn't mean you shouldn't have any security. Lockpicks exist, but we still lock our doors.
+
When done, it will output 2 files (id_ed25519.pub and id_ed25519) to ~/.ssh (If you used the default location). You will want to set the permissions for the private key used by the client
  
===Hardcore attackers===
+
chmod 600 ~/.ssh/id_ed25519
The last class is attackers with very high competence, extensive resources, who are highly motivated to come after ''you''. This is basically a government agency (CIA/NSA/FBI/Chinese spies) or a serious hacker (eg. hired by a company) targeting specifically you. Note that, as opposed to the 0day hacker from the previous class, these attackers are targeting specifically you. So the argument that they have "bigger fish to fry" does not apply anymore: Either the government is after you because you did something they don't like, or a someone paid a hacker to get you, either way the attacker will not stop until they've tried every trick in the book (and it's a very big book).
 
  
There isn't much you can do about this group. You could try to take some measures, but they will be very inconvenient, and some may even be dangerous or borderline illegal. For one, the government could easily gain physical access to your system by producing a warrant, and unlike a burglar, they actually could and would take advantage of that physical access. Given this, your best option is to not attract any attacks in the first place: Don't do anything illegal, don't be an important person targeted by cyber warfare, and don't piss off any hackers, or anyone who would pay a hacker. Anything beyond that is out of this document's scope.
+
To use the keys for ssh authentication just append the public key (id_ed25519.pub) to ~/.ssh/authorized_keys in the home directory of your admin user on your server.
  
== Recommended security policy==
+
Using sftp login as admin user:
Going by the above model, these recommendations aim to deter entirely the first two groups, deter as much of the third group as possible, without taking any additional measures for the fourth group.
 
  
=== GNU/Linux===
+
put ~/id_ed25519.pub
* If you are behind a router, only forward ports you need.
 
* When installing the OS, encrypt your entire drive (except for /boot which is needed to actually boot before the disk is unlocked). Because you need to enter a password at boot to decrypt, you will not be able to reboot remotely, but the alternative of not encrypting is unacceptable. Try not to kill your server when you're not around to boot it.
 
** Encrypting only your home directory is not adequate. There is sensitive data outside the home directory as well.
 
  
==== Protecting Your Private Network ====
+
Exit sftp, now use ssh to log in as your admin user and append the public key to the authorized keys file:
Use a [https://en.wikipedia.org/wiki/DMZ_%28computing%29 DMZ], nigger.
+
 +
mkdir ~/.ssh
 +
cat ~/id_ed25519.pub >> ~/.ssh/authorized_keys
 +
rm -rf ~/id_ed25519.pub
  
==== Securing your shell ====
+
Now take ownership of it:
  
If anyone breaks into your shell, you are FUCKED. They will own your whole server within minutesThere are bots that do nothing but scan for vulnerabilities on random IP addresses all day long, and they will hammer your SSH port like it's Natalie Portman's butthole. You need to secure that shit as your first priority, and here's how:
+
  chmod 700 ~/.ssh
 +
  chmod 600 ~/.ssh/authorized_keys
  
Add a non-root user.  Then, while logged in as root, do this:
+
DO NOT EXIT SSH YET, but open a second ssh session and connect to your server:
  
  visudo
+
  ssh faggot@server -i /dir/to/privatekey/id_ed25519 -o PasswordAuthentication=no -vv
  
Go down to the bit where it says ''# User privilege specification'', and copy the setup for the root line.  So, if your non-root user is "faggot," make it look like so:
+
If it all goes well, your login will look something like this:
  
  # User privilege specification
+
  Using username "faggot".
root    ALL=(ALL) ALL
+
  Authenticating with public key "ed25519-key-########"
faggot   ALL=(ALL) ALL
 
   
 
We are going to use [http://www.chiark.greenend.org.uk/~sgtatham/putty/download.html PuTTY] in this tutorial because its consistently available on almost all platforms, including GNU/Linux (check your repos) OSX, and Windows.  You can also use ssh-keygen for GNU/Linux or something else entirely, but if you already knew that, you probably wouldn't need this page, amirite?
 
  
The PuTTY suite includes a program called PuTTYGen.  Run PuTTYGen to generate a public/private key pair.  Go with SSH-2 DSA, 4096 bits - nobody's gonna crack that shit easily, and the [[NSA]] infiltrated the RSA, so fuck that.  When done, it will display your public key.  Except for the very beginning and very end, it will look like a shitton of gibberish - this is normal.  Copy and paste that text into a text file, but omit the last bit that says "dsa-key-########".  Put in a passphrase, this is not meant to authenticate you against the SSH server, but to keep the private key secure in case it's stolen from your client machine.  Save the private key.
+
Assuming that works, close your previous ssh session and open your sshd config to force publickey authentication:
  
Open PuTTY and log in as your non-root user. Then do this:
+
  sudo nano /etc/ssh/sshd_config
  
mkdir /home/faggot/.ssh
+
{{bc|sshd_config
nano /home/faggot/.ssh/authorized_keys
 
  
Paste in your public key that you saved as a text file. MAKE SURE IT IS ALL ONE LINE, like so:
+
  HostKey /etc/ssh/ssh_host_ed25519_key
 +
HostKey /etc/ssh/ssh_host_rsa_key
 +
HostKey /etc/ssh/ssh_host_ecdsa_key
  
  ssh-dsa [insanely long string of crap]
+
# Ciphers and keying
 +
HostKeyAlgorithms ssh-[email protected],ssh-ed25519
 +
KexAlgorithms curve25519-sha256
 +
 +
MACs hmac-sha2-512,[email protected]
  
And save it.
+
# Only allow incoming ECDSA and ed25519 sessions:
 +
HostbasedAcceptedKeyTypes ecdsa-sha2-nistp256,ecdsa-sha2-nistp384,ecdsa-sha2-nistp521,ssh-ed25519
 +
PubkeyAcceptedKeyTypes ecdsa-sha2-nistp256,ecdsa-sha2-nistp384,ecdsa-sha2-nistp521,ssh-ed25519
  
Now take ownership of it:
+
# Authentication:
 +
PermitRootLogin no
 +
AllowUsers faggot AdminUser
 +
MaxAuthTries 5
 +
MaxSessions 2
  
  chmod 600 ~/.ssh/authorized_keys
+
  AuthenticationMethods publickey
 +
PubkeyAuthentication yes
  
DO NOT LOG OUT OF PuTTY YET, but open a second PuTTY session and connect to your server, only this time point PuTTY to your private key file to test it out. If it all goes well, your login will look something like this:
+
# To disable tunneled clear text passwords, change to no here!
 +
PasswordAuthentication no
 +
 +
## Under PAM
 +
  UsePAM no
  
  Using username "faggot".
+
  AllowAgentForwarding no
  Authenticating with public key "dsa-key-########"
+
  AllowTcpForwarding no
 +
AllowStreamLocalForwarding no
 +
X11Forwarding no
  
Assuming that works, close your previous PuTTY session and do this:
+
ClientAliveInterval 900
 +
ClientAliveCountMax 0
  
  sudo nano /etc/ssh/sshd_config
+
  # override default of no subsystems
 +
Subsystem sftp /usr/lib/openssh/sftp-server -f AUTHPRIV -l INFO}}
  
You can change the SSH port here to a random number - that's optional though, because hacker bots are gonna find it anyhowBut if you do change it don't forget to change it in PuTTY as well. 
+
Save these changes and restart your SSH serverOn [[Debian]], or any other system using systemd, it would be:
  
But DO make the following changes:
+
sudo service ssh restart
  
  PermitRootLogin no
+
BOOM. Assuming all went well, you have now set up your shell so that 1) "root" cannot log in, 2) ONLY "faggot" can log in, and 3) "faggot" can ONLY log in using their private key file instead of a password. You'll still want to set up and install fail2ban or similar to secure things further.
  PasswordAuthentication no
 
X11Forwarding no
 
UsePAM no
 
  
Add the following to the bottom if missing:
+
Oh, and don't lose that private key file (id_ed25519).  You cannot recreate it, so losing it means you are doomed. Back it up in multiple places. You may wish to place a copy on a floppy drive (if you're a time-traveller from 1995) or USB stick as well, for safekeeping.
  
UseDNS no
+
==SSH config file==
AllowUsers faggot
+
A config file in the <code>~/.ssh/</code> directory enables you to set addresses, keyfiles and aliases for your servers.
  
If you have additional users, put a space after "faggot" and add the next user, and so on if you have more.
+
sudo nano ~/.ssh/config
  
Save these changes and restart your SSH server.  On [[Debian]], or any other system using sysvinit or OpenRC setup it would be:
+
Add:
  
  sudo /etc/init.d/ssh reload
+
  Host my-server
 +
  HostName 198.168.1.88
 +
  User faggot
 +
  IdentityFile ~/.ssh/id_ed25519
 +
  IdentitiesOnly yes
  
If you are using systemd, it would be:
+
Now you can login using <code>ssh my-server</code>
  
sudo systemctl restart sshd
+
==Troubleshooting==
 +
* Check permissions on keys and the ~/.ssh/ directory for your client and server
 +
* Ensure you edit the sshd_config on the server and ssh_config for client
 +
* Delete known_hosts in your client ssh directory after each authentication during setup until you have your sshd_config setup and a successful public key authentication
 +
* See [[Home server/Remote access#Firewall and Ports]]
  
BOOMAssuming all went well, you have now set up your shell so that 1) "root" cannot log in, 2) ONLY "faggot" can log in, and 3) "faggot" can ONLY log in using their private key file instead of a password. You'll still want to set up and install fail2ban or similar to secure things further.
+
=[http://www.fail2ban.org/wiki/index.php/Main_Page fail2ban]=
 +
fail2ban monitors your log files (any of them, not just SSH)If it sees too many login failures, it bans the offending IP for as long as you configure it to.  It won't prevent a distributed brute-force attack, but it will help a LOT. With the default settings, 3 failed SSH logins trigger a 10 minute ban for that IP. This makes brute-forcing very difficult. Usually hackers see the ban and move on, they don't bother even waiting for the 10 minutes to run out.
  
Oh, and don't lose that private key file. You cannot recreate it, so losing it means you are doomed. Back it up in multiple places. You may wish to place a copy on a floppy drive (if you're a time-traveller from 1995) or USB stick as well, for safekeeping.
+
* [https://www.linode.com/docs/guides/using-fail2ban-to-secure-your-server-a-tutorial/ Secure your server with fail2ban]
  
===== Securing your shell even more (and everything else) =====
+
sudo apt install fail2ban
  
Even with your shell secured, its still gonna get hammered, and that's going to get irritating quick. Given enough time, even your super-secret keyfile can eventually be guessed.  Well, guess what?  You can ban the SHIT out of those bots with fail2ban.
+
Copy both fail2ban.conf and jail.conf, fail2ban will update these two files and the local files will supersede these:
  
fail2ban monitors your log files (any of them, not just SSH). If it sees too many login failures, it bans the offending IP for as long as you configure it to. It won't prevent a distributed brute-force attack, but it will help a LOT.
+
sudo cp /etc/fail2ban/fail2ban.conf /etc/fail2ban/fail2ban.local && sudo cp /etc/fail2ban/jail.conf /etc/fail2ban/jail.local
  
*[https://www.digitalocean.com/community/articles/how-to-protect-ssh-with-fail2ban-on-debian-7 How To Protect SSH with fail2ban on Debian 7]
+
Edit the jail.local and uncomment sshd in the jail section:
*[https://www.digitalocean.com/community/articles/how-to-protect-ssh-with-fail2ban-on-centos-6 How To Protect SSH with fail2ban on CentOS 6]
 
*[https://www.digitalocean.com/community/articles/how-to-protect-ssh-with-fail2ban-on-ubuntu-12-04 How To Protect SSH with fail2ban on Ubuntu 12.04]
 
  
Please note that if you are going to install iRedMail (below), it will install and configure fail2ban for you.  You may still wish to tweak its settings though.
+
sudo nano /etc/fail2ban/jail.local
  
==== fail2ban ====
+
[sshd]
 +
enabled = true
 +
port = ssh
  
fail2ban is a utility that scans your system log files and bans anyone who tried to make logins and fails. With the default settings, 3 failed SSH logins trigger a 10 minute ban for that IP. This makes brute-forcing very difficult. Usually hackers see the ban and move on, they don't bother even waiting for the 10 minutes to run out.
+
Then restart fail2ban:
  
  sudo apt-get install fail2ban
+
  sudo service fail2ban restart
  
 
fail2ban comes with a bunch of rules already set up. To see these, type <code>sudo fail2ban-client -d</code> (fail2ban runs as root so you won't get anything without sudo). For best results, the jails should be reviewed and fine tuned. There is a manual here: http://www.fail2ban.org/wiki/index.php/MANUAL_0_8
 
fail2ban comes with a bunch of rules already set up. To see these, type <code>sudo fail2ban-client -d</code> (fail2ban runs as root so you won't get anything without sudo). For best results, the jails should be reviewed and fine tuned. There is a manual here: http://www.fail2ban.org/wiki/index.php/MANUAL_0_8
Line 132: Line 155:
 
fail2ban keeps a log where it records IPs it banned. You can see it with <code>nano /var/log/fail2ban.log</code>. After a few days, a bunch of Chinese IPs should pop up.
 
fail2ban keeps a log where it records IPs it banned. You can see it with <code>nano /var/log/fail2ban.log</code>. After a few days, a bunch of Chinese IPs should pop up.
  
To quickly analyze the banned IPs, run <code>cat /var/log/fail2ban.log | grep Ban</code>. Paste the resulting lines into text editor of your choice and replace the regex <code>.*Ban </code> with an empty string. You will now have the list of IPs. Paste these into a batch geolocator tool like [http://www.infobyip.com/ipbulklookup.php this one].
+
To quickly analyze the banned IPs, run <code>grep Ban /var/log/fail2ban.log</code>. Paste the resulting lines into text editor of your choice and replace the regex <code>.*Ban </code> with an empty string. You will now have the list of IPs. Paste these into a batch geolocator tool like [http://www.infobyip.com/ipbulklookup.php this one].
 
 
==== Protecting from DDoS and shit ====
 
Use [http://www.fail2ban.org/wiki/index.php/Main_Page Fail2Ban] (and/or [http://denyhosts.sourceforge.net/ DenyHosts]) and perhaps a redundant computer in the DMZ. Also never use passwords, only keyfiles.
 
  
==== [https://help.ubuntu.com/community/SinglePacketAuthorization fwknop - Single Packet Authorization] ====
+
=[[Wikipedia:Pork knocking|Port Knocking]]=
 
Normally, your server needs to keep a port open for each service you want to provide. However, hackers love trying to break in the moment they find an open port.
 
Normally, your server needs to keep a port open for each service you want to provide. However, hackers love trying to break in the moment they find an open port.
  
 
SPA solves the problem by keeping ports close when not in use. How does the server know to open them when you need to talk to it? You pick a port, say 12345, to use for SPA. The server listens on that port but never replies, so there is no way to tell that it's open (and everything else is closed). Every packet arriving on 12345 is actually inspected, the server is waiting for a packet that was encrypted with the correct key. Once a valid packet is detected, the server opens up the ports you need for a few minutes, letting you connect, and then closes them again (you stay connected).
 
SPA solves the problem by keeping ports close when not in use. How does the server know to open them when you need to talk to it? You pick a port, say 12345, to use for SPA. The server listens on that port but never replies, so there is no way to tell that it's open (and everything else is closed). Every packet arriving on 12345 is actually inspected, the server is waiting for a packet that was encrypted with the correct key. Once a valid packet is detected, the server opens up the ports you need for a few minutes, letting you connect, and then closes them again (you stay connected).
  
== Mail servers ==
+
* [https://help.ubuntu.com/community/SinglePacketAuthorization fwknop - Single Packet Authorization]
Obviously it's bad for your mail server to get compromised. If hackers break into a mail server, they can start sending spam, so these are high value targets. As soon as they find out that your mail ports are open (and they'll find out very quickly thanks to scanning ports+harvesting your address), they'll come right for you.
+
* [https://linoxide.com/firewall/knockd-protect-server-port/ Knockd]
 +
 
 +
=Firewall and Ports=
 +
* Don't forget to allow traffic on the ssh port (default 22)
 +
 
 +
sudo ufw allow ssh
 +
 
 +
* If you want to access your server from outside your home network you will need to forward port 22 on your router. A guide for port forwarding can be found [https://portforward.com/ here].
 +
 
 +
=External links=
 +
* [https://wiki.debian.org/SSH SSH]
 +
* [https://smallstep.com/blog/use-ssh-certificates/ SSH authentication using certificates]
 +
* [https://stinkyparkia.wordpress.com/2014/10/14/remote-unlocking-luks-encrypted-lvm-using-dropbear-ssh-in-ubuntu-server-14-04-1-with-static-ipst/ Unlock encrypted volume using Dropbear]
 +
 
 +
=See also=
 +
* [[Home server]]
 +
* [[Security]]
  
If your server starts sending spam, you will be taken for a spammer by all the major spammer blacklists. Your ISP may receive abuse complaints, and they'll be wanting to ask you wtf is going on. If the attacker does something illegal (eg. spam is illegal in Murka) you could get the authorities coming after your server, too. And when all this is over and the dust settled, you'll realize that your domain is now on every blacklist under the sun, all your emails bounce so you can't talk to anyone, and it's a huge pain to get off the blacklists ("I'm totally not a spammer guys, that was just a hacker!").
+
[[Category:Tutorials]]

Latest revision as of 09:21, 30 January 2021

SSH stands for Secure Shell and is a protocol for secure remote login and other secure network services over an insecure network, which basically means you can access your server from your computer over a network and execute commands as if you were typing them on the server itself. OpenSSH, the most popular SSH software, comes with a client and a server, the config files are /etc/ssh/ssh_config and /etc/ssh/sshd_config respectively. An OpenSSH server can also act as a file server using the sftp client. SFTP enables you to put and get files on and off your server, as well as many other things.

Setup

You usually enable the ssh server during the installation. Do this if possible, it is the simplest way.

  • If you did not setup ssh to auto start on boot, using systemd type:
sudo systemctl enable ssh && sudo systemctl start ssh
  • If that does not work, you need to install OpenSSH with your package manager
sudo apt install openssh-server

SSH keyfile authentication

We are going to use ssh & ssh-keygen in this tutorial because its consistently available on almost all platforms, including GNU/Linux, BSD, and OSX (by default), and Windows (You're not going to use wangblows and also worry about NSA backdoors are you?). You can also use PuTTY if you need a GUI crutch or something else entirely, but if you were a tard like that, you probably shouldn't use this page, amirite?

First make the ssh directory for your client:

mkdir ~/.ssh

OpenSSH includes a program called ssh-keygen. To generate a public/private key pair run:

ssh-keygen -a 256 -t ed25519
  • With ed25519 the default bitsize is plenty secure (the -b flag is ignored for ed25519 anyways) - nobody's gonna crack that shit easily, the NSA infiltrated the RSA, and DSA is old and insecure, so fuck that.
  • Optionally enter a strong password when prompted, this is not meant to authenticate you against the SSH server, but to keep the private key secure in case it's stolen from your client machine.

When done, it will output 2 files (id_ed25519.pub and id_ed25519) to ~/.ssh (If you used the default location). You will want to set the permissions for the private key used by the client

chmod 600 ~/.ssh/id_ed25519

To use the keys for ssh authentication just append the public key (id_ed25519.pub) to ~/.ssh/authorized_keys in the home directory of your admin user on your server.

Using sftp login as admin user:

put ~/id_ed25519.pub

Exit sftp, now use ssh to log in as your admin user and append the public key to the authorized keys file:

mkdir ~/.ssh
cat ~/id_ed25519.pub >> ~/.ssh/authorized_keys
rm -rf ~/id_ed25519.pub

Now take ownership of it:

chmod 700 ~/.ssh
chmod 600 ~/.ssh/authorized_keys

DO NOT EXIT SSH YET, but open a second ssh session and connect to your server:

ssh faggot@server -i /dir/to/privatekey/id_ed25519 -o PasswordAuthentication=no -vv

If it all goes well, your login will look something like this:

Using username "faggot".
Authenticating with public key "ed25519-key-########"

Assuming that works, close your previous ssh session and open your sshd config to force publickey authentication:

sudo nano /etc/ssh/sshd_config 
sshd_config

 HostKey /etc/ssh/ssh_host_ed25519_key
 HostKey /etc/ssh/ssh_host_rsa_key
 HostKey /etc/ssh/ssh_host_ecdsa_key

 # Ciphers and keying
 HostKeyAlgorithms [email protected],ssh-ed25519
 KexAlgorithms curve25519-sha256 
 Ciphers [email protected],[email protected]
 MACs hmac-sha2-512,[email protected]

 # Only allow incoming ECDSA and ed25519 sessions:
 HostbasedAcceptedKeyTypes ecdsa-sha2-nistp256,ecdsa-sha2-nistp384,ecdsa-sha2-nistp521,ssh-ed25519
 PubkeyAcceptedKeyTypes ecdsa-sha2-nistp256,ecdsa-sha2-nistp384,ecdsa-sha2-nistp521,ssh-ed25519

 # Authentication:
 PermitRootLogin no
 AllowUsers faggot AdminUser
 MaxAuthTries 5
 MaxSessions 2

 AuthenticationMethods publickey
 PubkeyAuthentication yes

 # To disable tunneled clear text passwords, change to no here!
 PasswordAuthentication no
 
 ## Under PAM
 UsePAM no

 AllowAgentForwarding no
 AllowTcpForwarding no
 AllowStreamLocalForwarding no
 X11Forwarding no

 ClientAliveInterval 900
 ClientAliveCountMax 0

 # override default of no subsystems
 Subsystem	sftp	/usr/lib/openssh/sftp-server -f AUTHPRIV -l INFO

Save these changes and restart your SSH server. On Debian, or any other system using systemd, it would be:

sudo service ssh restart

BOOM. Assuming all went well, you have now set up your shell so that 1) "root" cannot log in, 2) ONLY "faggot" can log in, and 3) "faggot" can ONLY log in using their private key file instead of a password. You'll still want to set up and install fail2ban or similar to secure things further.

Oh, and don't lose that private key file (id_ed25519). You cannot recreate it, so losing it means you are doomed. Back it up in multiple places. You may wish to place a copy on a floppy drive (if you're a time-traveller from 1995) or USB stick as well, for safekeeping.

SSH config file

A config file in the ~/.ssh/ directory enables you to set addresses, keyfiles and aliases for your servers.

sudo nano ~/.ssh/config

Add:

Host my-server
 HostName 198.168.1.88
 User faggot
 IdentityFile ~/.ssh/id_ed25519
 IdentitiesOnly yes

Now you can login using ssh my-server

Troubleshooting

  • Check permissions on keys and the ~/.ssh/ directory for your client and server
  • Ensure you edit the sshd_config on the server and ssh_config for client
  • Delete known_hosts in your client ssh directory after each authentication during setup until you have your sshd_config setup and a successful public key authentication
  • See Home server/Remote access#Firewall and Ports

fail2ban

fail2ban monitors your log files (any of them, not just SSH). If it sees too many login failures, it bans the offending IP for as long as you configure it to. It won't prevent a distributed brute-force attack, but it will help a LOT. With the default settings, 3 failed SSH logins trigger a 10 minute ban for that IP. This makes brute-forcing very difficult. Usually hackers see the ban and move on, they don't bother even waiting for the 10 minutes to run out.

sudo apt install fail2ban

Copy both fail2ban.conf and jail.conf, fail2ban will update these two files and the local files will supersede these:

sudo cp /etc/fail2ban/fail2ban.conf /etc/fail2ban/fail2ban.local && sudo cp /etc/fail2ban/jail.conf /etc/fail2ban/jail.local

Edit the jail.local and uncomment sshd in the jail section:

sudo nano /etc/fail2ban/jail.local
[sshd]
enabled = true
port = ssh

Then restart fail2ban:

sudo service fail2ban restart

fail2ban comes with a bunch of rules already set up. To see these, type sudo fail2ban-client -d (fail2ban runs as root so you won't get anything without sudo). For best results, the jails should be reviewed and fine tuned. There is a manual here: http://www.fail2ban.org/wiki/index.php/MANUAL_0_8

fail2ban keeps a log where it records IPs it banned. You can see it with nano /var/log/fail2ban.log. After a few days, a bunch of Chinese IPs should pop up.

To quickly analyze the banned IPs, run grep Ban /var/log/fail2ban.log. Paste the resulting lines into text editor of your choice and replace the regex .*Ban with an empty string. You will now have the list of IPs. Paste these into a batch geolocator tool like this one.

Port Knocking

Normally, your server needs to keep a port open for each service you want to provide. However, hackers love trying to break in the moment they find an open port.

SPA solves the problem by keeping ports close when not in use. How does the server know to open them when you need to talk to it? You pick a port, say 12345, to use for SPA. The server listens on that port but never replies, so there is no way to tell that it's open (and everything else is closed). Every packet arriving on 12345 is actually inspected, the server is waiting for a packet that was encrypted with the correct key. Once a valid packet is detected, the server opens up the ports you need for a few minutes, letting you connect, and then closes them again (you stay connected).

Firewall and Ports

  • Don't forget to allow traffic on the ssh port (default 22)
sudo ufw allow ssh
  • If you want to access your server from outside your home network you will need to forward port 22 on your router. A guide for port forwarding can be found here.

External links

See also