Hardening a Server: SSH Settings, Brute-Force Detection and an Open-Port Audit
Reduce what attackers can use: lint an SSH configuration against safe settings, find brute-force sign-in attempts in an authentication log and decide which addresses to block, and audit open ports against a list of what should be open, with two implementations of each check.
In this lesson you will
- Lint an SSH configuration
- Detect brute-force logins in a log
- Block by a counted threshold
- Audit open ports against an allow-list
About 28 minutes
Ten thousand people are trying the front door
Within hours of going online, a new server starts receiving sign-in attempts from all over the world. Automated programs try the SSH port, 22, with common user names and passwords, and the logs fill with “Failed password” lines. Most are harmless against a well-configured server, and the defence is to make the doors strong, and not to hope that nobody tries. Four habits cover much of the ground. Disable root login over SSH, so attackers must guess a user name as well. Disable password login and use keys, which cannot be guessed. Keep the list of open ports as short as possible, with only what the server really offers. And watch the logs for patterns, such as many failures from one address, and block them or alert.
Each habit can be checked by a program. A configuration linter reads sshd_config and compares settings with a list of safe values. A log analyser counts failed sign-ins per address in a time window and flags those above a threshold, which is how tools such as fail2ban decide to add a firewall rule for a while. A port audit compares the list of listening sockets with an allow-list and reports anything unexpected, since an unexpected listener, a database exposed on all addresses, a forgotten test server, is often the real hole. These checks are only useful when they run regularly and when someone reads the results. Also remember that hardening is layered: keys, a firewall, updates, least privilege and monitoring each reduce the chance and the damage of a failure in the others.
| Area | Safe setting | Why |
|---|---|---|
| SSH root login | PermitRootLogin no | Attackers need a user name too |
| SSH passwords | PasswordAuthentication no | Keys cannot be guessed |
| Open ports | Only what is needed | Less to attack |
| Failed logins | Block repeat offenders for a time | Stops brute force |
| Updates | Apply security updates promptly | Known holes are exploited fast |
# /etc/ssh/sshd_config (sample)
Port 22
PermitRootLogin yes
PasswordAuthentication yes
PubkeyAuthentication yes
PermitEmptyPasswords no
X11Forwarding yes
MaxAuthTries 6
AllowUsers deploy femi
import sys, json, re
SAFE = {"PermitRootLogin": ("no", "prohibit-password"), "PasswordAuthentication": ("no",), "PermitEmptyPasswords": ("no",), "X11Forwarding": ("no",), "PubkeyAuthentication": ("yes",)}
cfg = {}
for line in open(sys.argv[1]):
line = line.split("#")[0].strip()
if line: k, _, v = line.partition(" "); cfg[k] = v.strip()
findings = [k + " is " + cfg.get(k, "(default)") + ", should be " + " or ".join(v) for k, v in SAFE.items() if cfg.get(k) not in v]
if int(cfg.get("MaxAuthTries", "6")) > 4: findings.append("MaxAuthTries is " + cfg["MaxAuthTries"] + ", should be 4 or less")
if "AllowUsers" not in cfg: findings.append("no AllowUsers list")
print("\n".join("- " + f for f in findings)); print("DATA " + json.dumps(findings))
- PermitRootLogin is yes, should be no or prohibit-password
- PasswordAuthentication is yes, should be no
- X11Forwarding is yes, should be no
- MaxAuthTries is 6, should be 4 or less
The linter read the sample configuration and reported four findings: PermitRootLogin is yes, should be no or prohibit-password; PasswordAuthentication is yes, should be no; X11Forwarding is yes, should be no; MaxAuthTries is 6, should be 4 or less. The sample allows root to sign in over SSH, accepts passwords, forwards graphical sessions, and lets each connection try six passwords. It does well in three other places: it keeps key authentication on, refuses empty passwords, and has an AllowUsers list that names the two people who may sign in, which is itself a strong control. A second implementation in JavaScript, written separately, found the same four settings, so the findings do not depend on one parser’s treatment of comments and spaces. After changing the file you must test a new SSH session before closing the old one, so that a mistake does not lock you out, and reload the daemon.
import random, sys, datetime, json
rng = random.Random(5)
t = datetime.datetime(2024, 3, 4, 2, 0, 0); lines = []
attackers = ["203.0.113.50", "203.0.113.77", "198.51.100.9"]
for minute in range(180):
t0 = t + datetime.timedelta(minutes=minute)
for _ in range(rng.choice([0, 0, 0, 1])): # occasional typos by the real users
lines.append("%s sshd[1]: Failed password for deploy from 192.0.2.%d port 5%d" % (t0.strftime("%b %d %H:%M:%S"), rng.randrange(1, 20), rng.randrange(1000, 9999)))
if 40 <= minute < 60:
for _ in range(rng.randrange(8, 14)): lines.append("%s sshd[1]: Failed password for invalid user %s from %s port 4%d" % (t0.strftime("%b %d %H:%M:%S"), rng.choice(["admin", "root", "test", "oracle"]), attackers[0], rng.randrange(1000, 9999)))
if 100 <= minute < 110:
for _ in range(rng.randrange(3, 6)): lines.append("%s sshd[1]: Failed password for root from %s port 3%d" % (t0.strftime("%b %d %H:%M:%S"), attackers[1], rng.randrange(1000, 9999)))
if minute in (30, 70): lines.append("%s sshd[1]: Accepted publickey for femi from 192.0.2.5 port 22222" % t0.strftime("%b %d %H:%M:%S"))
open(sys.argv[1], "w").write("\n".join(lines) + "\n")
print("wrote", len(lines), "lines covering three hours")
wrote 299 lines covering three hours
import re, collections, json, sys
fails = collections.defaultdict(list)
for line in open(sys.argv[1]):
m = re.match(r"^(\w+ \d+) (\d+):(\d+):(\d+) sshd\[\d+\]: Failed password for (?:invalid user )?(\S+) from (\S+) port", line)
if m: fails[m.group(6)].append(int(m.group(2)) * 60 + int(m.group(3)))
THRESHOLD, WINDOW = 10, 10 # 10 failures within 10 minutes from one address
blocked = {}
for ip, times in fails.items():
times.sort()
for i, t in enumerate(times):
if sum(1 for u in times[i:] if u < t + WINDOW) >= THRESHOLD: blocked[ip] = len(times); break
for ip, n in sorted(fails.items(), key=lambda x: -len(x[1])): print(ip.ljust(15), len(n), "failures", "-> BLOCK" if ip in blocked else "")
print("DATA " + json.dumps({"fails": {ip: len(n) for ip, n in fails.items()}, "blocked": sorted(blocked)}))
203.0.113.50 213 failures -> BLOCK
203.0.113.77 39 failures -> BLOCK
192.0.2.8 5 failures
192.0.2.6 5 failures
192.0.2.12 4 failures
192.0.2.5 3 failures
192.0.2.10 3 failures
192.0.2.14 3 failures
192.0.2.13 3 failures
192.0.2.9 2 failures
192.0.2.18 2 failures
192.0.2.2 2 failures
192.0.2.3 2 failures
192.0.2.15 2 failures
192.0.2.7 2 failures
192.0.2.16 2 failures
192.0.2.1 2 failures
192.0.2.19 1 failures
192.0.2.4 1 failures
192.0.2.17 1 failures
213 203.0.113.50
39 203.0.113.77
5 192.0.2.8
5 192.0.2.6
4 192.0.2.12
3 192.0.2.5
3 192.0.2.14
3 192.0.2.13
3 192.0.2.10
2 192.0.2.9
2 192.0.2.7
2 192.0.2.3
2 192.0.2.2
2 192.0.2.18
2 192.0.2.16
2 192.0.2.15
2 192.0.2.1
1 192.0.2.4
1 192.0.2.19
1 192.0.2.17
The generated authentication log covers three hours. It holds occasional typos by real users spread over 18 ordinary addresses, one long burst of attempts against many user names from a single address, 203.0.113.50 with 213 failures in 20 minutes, a shorter burst of attempts on the root account from a second address, 39 failures in 10 minutes, and two normal key sign-ins. The program groups the failures by address and applies a rule: 10 failures within 10 minutes from one address means block. It blocks both attackers, 203.0.113.50 and 203.0.113.77, and none of the real users, whose most active address made only 5 failed attempts in the whole three hours. The gap between the busiest honest address, 5, and the quietest attacker, 39, is wide, which is what makes a threshold such as 10 safe here. In real life the gap is narrower, and a slow attacker who tries one password a minute stays below any such rule, which is a good reason to also disable root login and passwords, as the linter said, so that guessing cannot succeed.
Independent check: the counts per address were also produced by a different tool chain, grep, awk, sort and uniq, shown above, and they match the program’s counts for every address, which shows that the parsing is right. The blocking decision rests on the threshold and the window, and those are choices: a threshold that is too low blocks forgetful users, and one that is too high lets a slow attacker through, which is why such tools add temporary bans that expire, and a whitelist of your own addresses.
import json
allowed = {22: "ssh", 80: "http", 443: "https"}
listening = {22: "0.0.0.0", 80: "0.0.0.0", 443: "0.0.0.0", 3306: "0.0.0.0", 5432: "127.0.0.1", 8080: "0.0.0.0"} # port -> bound address, as read from the kernel
problems = []
for port, addr in sorted(listening.items()):
if port not in allowed and addr != "127.0.0.1": problems.append("port %d is open to the network but not on the allow-list" % port)
elif port not in allowed: problems.append("port %d is listening on localhost only: fine, but not on the allow-list" % port)
for port in allowed:
if port not in listening: problems.append("expected port %d is not listening" % port)
print("\n".join("- " + p for p in problems)); print("DATA " + json.dumps(problems))
- port 3306 is open to the network but not on the allow-list
- port 5432 is listening on localhost only: fine, but not on the allow-list
- port 8080 is open to the network but not on the allow-list
The port audit compares what is listening with what should be. In the example, a database on 3306 and a test server on 8080 are open to the whole network and are not on the allow-list: those two are the real findings, and the database one is the dangerous one. The second database on 5432 listens only on localhost, which is acceptable and reported as information. The list of listening ports would come from the kernel, as lesson 2 showed, and the same audit can run every hour from a cron job and send the result to the person responsible. Here the comparison of an expected list with an actual one is the whole technique, and it also catches the opposite problem, a service that should be running and is not.
Check by hand: the linter’s four findings are the settings that differ from the safe list, root login, passwords, X11 forwarding and the number of tries. The first brute-force address made 8 to 13 attempts per minute for 20 minutes, which passes the threshold of 10 in 10 minutes within the first two minutes, and the second made 3 to 5 a minute for 10 minutes, which also passes it. For the ports, three of the six listeners are on the allow-list.
Before you disable passwords or root login, open a second session with a key and test it. A mistake in sshd_config can lock you out of the only way into the server.
These three remove most of the risk for a small server. Block everything except the ports you need, and apply security updates promptly.
Providers, plans and prices change often, so the lessons use invented prices and generic names, and you must check each provider’s current website. The server behaviour in this lesson was run for real on a Linux machine with Python 3.13, Node.js 22, OpenSSL and standard Unix tools, and every result was checked a second way. Tools such as fail2ban automate the blocking, and cloud providers have their own firewalls. Check the documentation of what you use.
Practice
Add a rule that flags attempts on the root account whatever their number. Write the allow-list for a server that also runs a mail server. Run the linter on the sshd_config of a machine you own.
Check what you learned
Five quick questions. Pick an answer and you will see straight away whether it is right and why.
Why disable root login over SSH?
- It speeds up the server
- Root has no password
- SSH needs it off
- Attackers must also guess a user name
And limits damage.
Why prefer keys to passwords?
- Keys are shorter to type
- Passwords are illegal
- Keys cannot be guessed by brute force
- Keys are slower
Disable password authentication.
What does a brute-force rule count?
- Successful logins
- Open ports
- Failed logins per address in a time window
- Files
Then block for a time.
Why audit open ports against an allow-list?
- It is a law
- Unexpected listeners are often the real hole
- It speeds up ports
- It reduces logs
A database open to the network.
Why test a second SSH session before changing settings?
- It is faster
- A mistake could lock you out
- It is required by SSH
- It adds users
Keep a way in.
Summary
- Disable root and password login for SSH; use keys.
- Count failed logins per address in a window and block offenders.
- Audit open ports against an allow-list.
- Run the checks regularly and read the results.
Questions
Should I change the SSH port?
It reduces noise in the logs and does not stop a determined attacker. It is not a substitute for keys and a firewall.
What is fail2ban?
A tool that reads logs and adds temporary firewall rules for addresses that fail too often. It automates the block decision that this lesson describes.
How often should I update?
Apply security updates promptly, and automatically where safe, and restart services that need it. Known holes are exploited within days.
