Skip to content

How to close MySQL port 3306 in WHM and cPanel without breaking sites

A PCI scan flagged port 3306 and turning off Remote MySQL did not close it. Here is how to find every client that still uses 3306, close the port in CSF and WHM, and roll back in one line if a site goes down.

There is no checkbox in WHM that closes MySQL’s port. Removing an entry from Remote MySQL, or deleting a host under WHM » Home » SQL Services » Additional MySQL Access Hosts, only changes which credentials MySQL will accept — the port stays open and a vulnerability scan keeps reporting it. What actually closes 3306 is the firewall: remove 3306 from TCP_IN in /etc/csf/csf.conf, add a scoped tcp|in|d=3306|s=<ip> line to /etc/csf/csf.allow for each source that genuinely needs it, then run csf -r. On a stock cPanel build with ConfigServer Firewall (CSF), TCP_IN often still lists 3306 — a global allow that lets any source IP reach the port, however short your Remote MySQL allowlist.

Most people arrive here because a scan report told them to close 3306, and the real question is how to do it without taking a site down. So the order below is deliberate: find out who is connecting first, then close the port, then keep a rollback in reach.

What you’ll accomplish

  • An inventory of every client that reaches 3306 from off the server, so you close the port knowing what you are cutting.
  • Port 3306 reachable only from a short list of named source IPs, or from nowhere at all.
  • Confirmation from an outside host that the port reads filtered, not open — the state a scan needs before it stops reporting the finding.
  • MySQL’s bind-address set deliberately, so a firewall mistake is not the only thing between the database and the internet.
  • A rollback you can run in one line if a site starts throwing database errors.

Prerequisites

  • Root SSH access to the cPanel server. Everything here is done from the shell; the WHM plugin UI can do the same edits, but it hides which file changed.
  • CSF installed and enabled. Check with csf -v and confirm TESTING = "0" in /etc/csf/csf.conf. If CSF is not present, see installing and configuring CSF on cPanel first.
  • If the host does not run CSF, the concepts hold but the commands do not: on firewalld you would use firewall-cmd --remove-port=3306/tcp plus a rich rule scoped to a source. Never mix CSF with hand-written iptables rules — CSF rewrites the chains it owns on every restart, and your manual rule disappears on the next csf -r.
  • A second SSH session, already connected, kept open for the entire procedure. Do not close it. If a firewall change locks you out, that live session is how you undo it. If you have one way in and no provider console, stop and arrange console access first.
  • A maintenance window. The inventory keeps this uneventful, but an old server usually hides a forgotten client.

How it works

Two separate systems decide whether a remote client can query your database, and they do not know about each other.

Gate one is the packet filter. CSF compiles /etc/csf/csf.conf, /etc/csf/csf.allow, and /etc/csf/csf.deny into iptables (or nftables) rules. TCP_IN lists ports accepted from any source address. It is not an allowlist of who may connect — it says the port is open to the internet. Per-source restrictions live in csf.allow, the only place a source IP is actually named.

Gate two is authentication. MySQL grants are scoped by host: 'appuser'@'203.0.113.42' is a different account from 'appuser'@'localhost'. cPanel’s Remote MySQL screen (and WHM’s Additional MySQL Access Hosts) is a front end for those host-scoped grants. “Enabling Remote MySQL” only tells cPanel it may create non-localhost grants.

Putting all your confidence in gate two is the failure mode: a password only matters once an attacker has already reached the service.

Three lanes crossing a firewall gate then a credential gate: an allowlisted office IP passes both, a scanner is dropped at the firewall, and a host reaching an open TCP_IN faces only the password

A third layer sits between them: bind-address. Bound to 127.0.0.1, MySQL never listens publicly and no firewall rule can make remote access work. Bound to 0.0.0.0, it listens everywhere and the firewall is your only barrier. Set it on purpose.

What a scan is actually reporting

An external vulnerability scan has no credentials and needs none. It completes a TCP handshake on 3306 and reads whatever the service says first — and MySQL and MariaDB both send a greeting packet with the protocol number and full server version string before authentication begins. The scanner records a reachable database service and a version number without attempting a login.

That is why tightening grants does nothing for the report. A host with no grant still gets a completed handshake and a courteous Host is not allowed to connect to this MySQL server reply — further confirmation that MySQL is listening. Emptying the Remote MySQL list changes gate two and leaves gate one untouched.

What removes the finding is a handshake that never completes from the scanner’s source address: in nmap terms filtered or closed, never open. Allowlist a CIDR containing the scanning service and the finding survives your change. And “closed” to a scanner is not “closed” to your applications — sites on the same server reach MySQL over localhost or a socket and never touch the firewall, while anything configured against the public address does. That is the set you have to find first. None of this makes a server compliant with anything; it removes one reachability finding from a report.

Step-by-step

  1. Confirm the exposure from outside. Testing from the server tells you nothing — loopback traffic never passes the firewall. Run this from a laptop or another host:

    nmap -Pn -sV -p 3306 203.0.113.10
    PORT     STATE SERVICE VERSION
    3306/tcp open  mysql   MariaDB 10.6.18

    The VERSION column is the greeting packet a scanner reads without logging in. Without nmap, nc -zv 203.0.113.10 3306 gives the same signal — a succeeded line means open.

  2. Find out who is actually connecting. The step people skip, and why closures cause outages. A snapshot misses the nightly backup and the weekly report, so sample established sessions on 3306 across a business cycle from screen, then collapse the log into distinct peers:

    while :; do ss -tnH state established '( sport = :3306 )' >> /root/3306-clients.log; sleep 60; done
    awk '{print $4}' /root/3306-clients.log | cut -d: -f1 | sort | uniq -c | sort -rn
        418 203.0.113.42
         96 198.51.100.17
          3 45.146.164.110

    A state filter drops the State column, so the peer address is field four. Two of those are clients; the third is a scanner that got a handshake. Track every address to a named system before calling it disposable.

  3. List the grants that permit remote logins. These name clients that were not connected during your sample:

    mysql -e "SELECT user, host FROM mysql.user WHERE host NOT IN ('localhost', '127.0.0.1', '::1') ORDER BY host;"
    +---------+---------------+
    | user    | host          |
    +---------+---------------+
    | appuser | 198.51.100.17 |
    | olduser | %             |
    +---------+---------------+

    On MariaDB 10.4 and later mysql.user is a view over mysql.global_priv and the query works unchanged. A % host accepts that user from anywhere, so while the port is open the password is the only control. Cross-check the UI: server-wide entries under WHM » Home » SQL Services » Additional MySQL Access Hosts, per-account copies under cPanel » Databases » Remote MySQL.

  4. Find applications configured against the public address, not localhost. These break the moment the port closes, and stay invisible until then:

    grep -rIhs "DB_HOST" /home/*/public_html/wp-config.php | sort | uniq -c | sort -rn
         41 define( 'DB_HOST', 'localhost' );
          2 define( 'DB_HOST', '203.0.113.10' );
          1 define( 'DB_HOST', '203.0.113.10:3306' );

    Three sites are taking a round trip out to the public interface to reach a database on the same disk. Sweep non-WordPress document roots for the server’s own address the same way, and fix them before touching the firewall. Moving DB_HOST to localhost changes which grant MySQL matches, so each affected user needs a 'user'@'localhost' grant too.

    Decision tree of who still needs 3306: the local app moves to localhost, a fixed remote server uses the private interface or a scoped csf.allow line, a person uses an SSH tunnel, a vendor CIDR is last resort

  5. Check what is listening and how MySQL is bound.

    ss -ltnp | grep 3306
    grep -R "bind-address\|skip-networking" /etc/my.cnf /etc/my.cnf.d/ 2>/dev/null
    LISTEN 0  151  0.0.0.0:3306  0.0.0.0:*  users:(("mariadbd",pid=1842,fd=25))
    /etc/my.cnf:bind-address = 0.0.0.0

    0.0.0.0:3306 means MySQL listens on every interface; 127.0.0.1:3306 means loopback-only, and no firewall change will make a remote client connect. No output from the second command means the directive is unset — also all interfaces. If your inventory found no legitimate off-box client, set bind-address = 127.0.0.1 under [mysqld] and restart MySQL: it then stops listening publicly at all, which no firewall reload can undo.

  6. See what CSF allows now. Two commands, and they must agree:

    grep "^TCP_IN" /etc/csf/csf.conf
    csf -l | grep 3306
    TCP_IN = "20,21,22,25,53,80,110,143,443,465,587,993,995,2077,2078,2082,2083,2086,2087,2095,2096,3306"
    ACCEPT  tcp  --  0.0.0.0/0  0.0.0.0/0  tcp dpt:3306

    If 3306 appears in TCP_IN, the port is open to the world right now regardless of what csf.allow says. csf -l prints the live iptables rules, and those are the authority — csf.conf is only intent until CSF restarts.

  7. Remove 3306 from TCP_IN. Copy the file first, then edit /etc/csf/csf.conf so the line reads without 3306:

    cp /etc/csf/csf.conf /etc/csf/csf.conf.bak-$(date +%F)
    (no output; confirm with ls /etc/csf/csf.conf.bak-*)
    TCP_IN = "20,21,22,25,53,80,110,143,443,465,587,993,995,2077,2078,2082,2083,2086,2087,2095,2096"

    Do not restart yet. Add the allow rules first so authorised clients never see an outage window.

  8. Add a scoped allow for each source that survived the inventory. Append to /etc/csf/csf.allow:

    # Office static IP - app deploys
    tcp|in|d=3306|s=203.0.113.42
    # Reporting VPC
    tcp|in|d=3306|s=198.51.100.0/24

    The format is protocol|direction|d=destination_port|s=source_ip, CSF’s advanced allow syntax, documented in the comment header of csf.allow itself. Two common errors: d= is the destination port on your server, not the client’s source port, so s=3306 matches nothing; and csf -a 203.0.113.42 does not do this — it allows that IP to every port on the box. Port-scoped allows go into csf.allow directly.

  9. Restart CSF and verify the compiled rules.

    csf -r
    csf -l | grep 3306
    csf and lfd have been restarted
    ACCEPT  tcp  --  203.0.113.42  0.0.0.0/0  tcp dpt:3306
    ACCEPT  tcp  --  198.51.100.0/24  0.0.0.0/0  tcp dpt:3306

    You want exactly those scoped ACCEPT lines and no rule with a source of 0.0.0.0/0 on 3306. If a wide-open rule survives, TCP_IN was not saved or a second config file is in play.

  10. Keep the rollback in reach. If a site starts failing, a temporary allow beats re-editing csf.conf under pressure — it expires by itself, so a rushed rescue does not quietly become permanent:

    csf -ta 203.0.113.42 3600 -p 3306 -d in
    csf: 203.0.113.42 allowed on port 3306 for 3600 seconds inbound

    The TTL takes suffixes, so 1d is a day. csf -t lists temporary entries, csf -tr removes one, csf -tf flushes them all.

  11. Create the matching grant. The firewall now passes the packet; MySQL still has to accept the credentials. Add the client IP under WHM » SQL Services » Additional MySQL Access Hosts, or from the shell:

    mysql -e "CREATE USER 'appuser'@'203.0.113.42' IDENTIFIED BY 'a-long-random-password'; GRANT SELECT, INSERT, UPDATE, DELETE ON appdb.* TO 'appuser'@'203.0.113.42'; FLUSH PRIVILEGES;"
    (no output on success; an existing user returns ERROR 1396)

    Use the exact IP, never % — 'appuser'@'%' accepts that user from anywhere and turns the firewall back into your only control. See the MySQL documentation for grant syntax and cPanel’s documentation for how the Remote MySQL screen maps onto grants.

  12. Better: do not open the port at all. For anyone on a laptop, a dynamic IP, or a machine you do not control, an SSH tunnel is stronger and needs no firewall change. Port 22 is already open and protected by keys:

    ssh -N -L 3307:127.0.0.1:3306 root@203.0.113.10
    (no output; the tunnel holds the terminal while it is up)

    Then, in another terminal:

    mysql -h 127.0.0.1 -P 3307 -u appuser -p appdb
    Welcome to the MariaDB monitor.
    MariaDB [appdb]>

    The tunnel terminates on the server, so from MySQL’s point of view the connection arrives from localhost — the grant you need is 'appuser'@'localhost', not the client’s public IP. That trips people up the first time. Nothing new is exposed, no allowlist needs upkeep when a home IP changes, and 3306 stays closed for good.

Three postures for remote MySQL access on cPanel with a verdict on each: 3306 open in TCP_IN, 3306 scoped through csf.allow, and 3306 closed with access over an SSH tunnel

Validate it works

Test from two places; one alone proves nothing.

From a disallowed IP, any machine not in csf.allow:

nmap -Pn -p 3306 203.0.113.10
PORT     STATE    SERVICE
3306/tcp filtered mysql

filtered is what you want: CSF’s default DROP policy discards the packet with no reply, so no version banner is disclosed. nc -zv 203.0.113.10 3306 should hang and time out rather than be refused. closed is still blocked, but means DROP = "REJECT" in csf.conf — the port sends an RST, confirming a host is alive. Either state clears a reachability finding; DROP is the better default.

From an allowed IP, the same scan should read open, and a real connection should work:

mysql -h 203.0.113.10 -P 3306 -u appuser -p appdb -e "SELECT 1;"
+---+
| 1 |
+---+
| 1 |
+---+

An open port with no successful login means the firewall is right and the grant is wrong; a filtered port from an allowed IP means the csf.allow line has a typo or never loaded.

Then load the sites. The firewall is only half of what you changed. Open the busiest sites, including any whose DB_HOST you edited, and confirm they render instead of showing a database error. Watch /var/log/lfd.log and the MySQL error log for an hour: if the port is genuinely filtered, remote hosts cannot reach the service, so new failures there come from something you missed. Finally, request a rescan — nothing in the report updates on its own, and the scan must run after csf -r from an address outside your allowlist.

Troubleshooting

Sites now show a database connection error. Almost always an application whose DB_HOST pointed at the server’s public address rather than localhost: the site was crossing the firewall to reach a database on its own disk, and you closed that path. Run csf -ta <client-ip> 3600 -p 3306 -d in to restore access while you work, then set DB_HOST to localhost and confirm a 'user'@'localhost' grant exists — skip the grant and you trade error 2003 for 1045. Search the whole document root, not just wp-config.php: caching plugins, .env files, and cron scripts each keep their own copy of the connection string.

A monitoring, backup, or reporting agent went quiet. These fail silently: the symptom is missing data, not an error anyone sees. If a graph flatlined or a backup stopped appearing after the change, the agent was polling 3306 from off the server. Two honest fixes — add its address to csf.allow like any other client, or move the check on-box so it runs over localhost. Look within a day, while the cause is obvious.

You locked yourself out, or the rules keep reverting. Lockout usually comes from editing TCP_IN and dropping 22, or from a csf.allow line with a bad character that makes CSF discard the whole file. This is why the second SSH session exists — in it, run csf -x to disable the firewall, fix the file, then csf -e. If both sessions are gone, you need the provider’s console. TESTING = "1" before a risky change is an automatic rescue: cron runs csf -f on the TESTING_INTERVAL, so a bad rule cannot strand you — but nothing you configure survives either, which explains rules that vanish minutes later. Set TESTING = "0" and run csf -r once access is verified. Full path: what to do when CSF blocked your own IP.

The connection fails from an address you allowed. The error number says which gate refused. Can't connect to MySQL server (2003) means the packet never reached the service: check that csf -l | grep 3306 shows your source, then ss -ltnp | grep 3306 — if MySQL is bound to 127.0.0.1, remote access is impossible however perfect the rule is. Many providers also apply a security group in front of the host, and a cloud-level block looks identical to a CSF one. Access denied (1045) and Host is not allowed to connect (1130) mean the opposite: the firewall worked, the credentials did not. Confirm the address MySQL sees, because behind NAT the client’s public IP is rarely the one it thinks it has:

mysql -e "SELECT user, host FROM mysql.user WHERE user = 'appuser';"
+---------+---------------+
| user    | host          |
+---------+---------------+
| appuser | 203.0.113.42  |
+---------+---------------+

3306 is open again after a CSF upgrade or a WHM plugin save. csf -u and the “Firewall Configuration” form in the WHM plugin both rewrite csf.conf. An upgrade can reintroduce defaults, and saving the form re-serialises whatever is in the TCP_IN field at that moment — including 3306 if someone loaded the page before your change. Re-check grep "^TCP_IN" /etc/csf/csf.conf after any upgrade and after anyone touches the plugin UI. Keep TCP_IN under configuration management so drift is caught rather than found by the next scan.

When this is the wrong approach

Scoping 3306 to named IPs mitigates a situation that should often not exist. Before building an allowlist, ask whether the database needs to be internet-reachable at all:

  • The application runs on the same server. MySQL should be on 127.0.0.1 (or a socket) and 3306 should never appear in a firewall rule. This is most cPanel sites, and why the DB_HOST sweep pays for itself.
  • The application runs on a different server in the same facility. Use the private interface. Bind MySQL to the private IP and scope the rule to the private range — the public internet is not part of that conversation.
  • A developer or a reporting tool needs occasional access. SSH tunnel. Access is tied to a key you can revoke in one line, the port stays closed, and nobody files a ticket when their home IP changes.
  • A SaaS product needs access from a range you do not control. Push back before allowlisting a vendor’s whole CIDR. A read replica, an API, or a scheduled export usually removes the requirement, and a vendor range is wide enough that a scan may reach you through it.

An allowlisted 3306 is the right answer when a small, genuinely fixed set of external addresses needs direct SQL and nothing above fits — a narrower set of cases than the number of servers with 3306 open suggests.

If this is the kind of work you’d rather never own again, it’s the daily job of Managed Cloud Ops — book an infrastructure review.