Sub topic 9
Limiting access with a firewall
A database server should accept connections only from the hosts that need them. You already control this inside the database with listen addresses and host-based authentication. A host firewall adds a second layer outside the database process. If a configuration mistake makes the server listen on every interface, the firewall can still block unwanted clients.
This chapter assumes you are comfortable with the Linux command line and sudo, and that you know what an IP address, a port and a CIDR range such as 10.0.0.0/24 are. It uses ufw on Debian or Ubuntu. The ideas carry over to firewalld, nftables and cloud security groups.
Why a firewall in addition to database settings
Each control sits at a different point in the path of a connection.
| Layer | Control | What it decides |
|---|---|---|
| Network | Host firewall | Whether a packet reaches the port at all |
| Network | Listen address (`listen_addresses`, `bind-address`) | Which local interface accepts connections |
| Database | `pg_hba.conf` or MySQL host patterns | Whether a given user, database and source address may continue |
| Database | Password or other authentication | Whether the client proves who it is |
The controls overlap on purpose. A mistake in one layer is then not enough to expose the data. A firewall also stops unwanted clients from reaching the authentication code, which shrinks the attack surface and keeps port scans and password guessing out of your logs.
Default ports
- PostgreSQL listens on TCP port 5432 by default.
- MySQL listens on TCP port 3306 by default.
If you changed port in the configuration, use that value in the firewall rules. Confirm what the server actually uses before writing rules:
ss -ltnp | grep -E ':(5432|3306)'Allowing the private subnet only
The rule below allows the PostgreSQL port from the application subnet and nothing else. Use 3306 for MySQL.
sudo ufw allow from 10.0.0.0/24 to any port 5432 proto tcp
sudo ufw status numberedThe rule has these parts:
from 10.0.0.0/24limits the source to that subnet.to any port 5432applies to any local address on that port.proto tcprestricts the rule to TCP, which is all either database uses for network clients.
To allow a single application host, give its address instead of a range, for example from 10.0.0.20. Narrower is better. A subnet is convenient but admits every machine in it.
Order of operations: do not lock yourself out
ufw is not active until you enable it, and enabling it with a default of deny incoming blocks SSH unless you allow it first. If you are connected over SSH, allow SSH before you turn the firewall on:
sudo ufw allow from 10.0.0.0/24 to any port 22 proto tcp
sudo ufw default deny incoming
sudo ufw default allow outgoing
sudo ufw enable
sudo ufw status verboseAdjust the SSH source to match where you actually administer the host from. If you use a non-standard SSH port, use that port. When you work on a remote machine you cannot reach physically, keep your current session open and test a second SSH login before you close it.
Reading and removing rules
ufw status numbered prints each rule with an index:
Status: active
To Action From
-- ------ ----
[ 1] 22/tcp ALLOW IN 10.0.0.0/24
[ 2] 5432/tcp ALLOW IN 10.0.0.0/24Delete a rule by its number, or by repeating its definition with delete:
sudo ufw delete 2
sudo ufw delete allow from 10.0.0.0/24 to any port 5432 proto tcpNumbers shift after each deletion. Run status numbered again before deleting a second rule.
Testing the result
Test from both sides. From an allowed application host, check that the port answers and that a login works:
nc -vz 10.0.0.5 5432
psql "host=10.0.0.5 dbname=appdb user=appuser sslmode=require"From a host outside the allowed range, the same nc command should time out. The difference between failure types tells you which layer blocked the connection:
| Symptom from the client | Likely cause |
|---|---|
| Timeout with no reply | The firewall drops the packet silently |
| "Connection refused" | The packet arrived, but nothing listens on that address and port, or a reject rule applies |
| Authentication or "no pg_hba.conf entry" error | The firewall and listener are fine, and the database rejected the client |
A timeout is the usual signature of a ufw deny. A refusal points at the listen settings, so check ss -ltnp on the server.
Edge cases and gotchas
- IPv6.
ufwhandles IPv6 ifIPV6=yesis set in/etc/default/ufw. If the database listens on::and your rules cover only IPv4, the IPv6 path may behave differently from what you tested. Keeplisten_addressesorbind-addressto the specific addresses you intend. - Docker. Published container ports are inserted into the firewall by Docker ahead of
ufwrules, so aufwrule may not block a containerized database. If your database runs in a container, bind the published port to a private address, for example-p 10.0.0.5:5432:5432. - Managed rules elsewhere. Cloud security groups and network firewalls apply in addition to the host firewall. A connection must pass all of them, so check each when a client cannot connect.
- Local connections. Applications on the same host connect over a Unix socket or loopback. The default
ufwconfiguration allows loopback traffic, so these need no rule. - Replication. A replica connects to the primary's database port. Add a rule for each replica host, and keep it as narrow as the application rules.
- Rule persistence.
ufwrules persist across reboots once the firewall is enabled. Verify withsudo ufw statusafter a reboot during maintenance. - Source address changes. If clients pass through NAT or a proxy, the database sees the proxy's address. Write the rule, and
pg_hba.confor the MySQL host pattern, for the address the server actually sees.
Matching the firewall to the database settings
Keep the three settings consistent. Using the examples from earlier chapters, the same subnet appears in each place:
# postgresql.conf
listen_addresses = 'localhost,10.0.0.5'
# pg_hba.conf (TYPE DATABASE USER ADDRESS METHOD)
hostssl appdb appuser 10.0.0.0/24 scram-sha-256sudo ufw allow from 10.0.0.0/24 to any port 5432 proto tcpWhen a client cannot connect, walk the layers in order: firewall rule, listening socket, authentication entry, then credentials. Changing the subnet in one place without updating the others is a common cause of lost connectivity after a network renumbering.
Exercise
A client on 10.0.1.15 tries to reach a PostgreSQL server at 10.0.0.5 and the connection hangs until it times out. The server has the rule ufw allow from 10.0.0.0/24 to any port 5432 proto tcp. Which layer is most likely responsible, and how do you fix it safely?
Show answer
The firewall is the likely cause. 10.0.1.15 is outside 10.0.0.0/24, so the default-deny policy drops its packets silently, which produces a timeout rather than a refusal. Add a rule for the narrowest source that covers the client, for example sudo ufw allow from 10.0.1.15 to any port 5432 proto tcp. Also add a matching pg_hba.conf entry for that address, then reload PostgreSQL, because the firewall rule alone will only move the failure to the "no pg_hba.conf entry" error.
Exercise
You are connected to a remote server over SSH and want to enable ufw with a default-deny incoming policy. What should you do first, and why?
Show answer
Allow SSH from your administration address (for example sudo ufw allow from 10.0.0.0/24 to any port 22 proto tcp) before running sudo ufw enable. Otherwise the default-deny policy blocks your own SSH session on the next connection and can lock you out. Keep the current session open and verify a second login before closing it.