TechEarl

How to Disable Root Login on Linux

Disable direct root login over SSH and on the console, lock the root password, switch sshd to key-only authentication, audit its algorithms with ssh_scan, and add a pre-auth login banner, without locking yourself out.

Ishan KarunaratnePublished ⏱️ 17 min readUpdated
Share thisCopied
Disable root login over SSH and the console, lock the root password, switch sshd to keys only, and add a pre-auth banner without locking yourself out.

To disable root login on Linux, set PermitRootLogin no in sshd_config to block root over SSH, then lock the root password with passwd -l root so console and su access close too. You then log in as a normal user and elevate with sudo. Make sure that sudo-capable account works first, or you will lock yourself out.

Direct root login is the account every attacker tries first, and it leaves no record of who did what. This page also covers the rest of a sensible sshd_config lockdown: turning off password authentication so only keys get in, auditing the algorithms the daemon offers with ssh_scan, and showing a login banner before authentication for the legal notice.

Step 0: confirm you have a way back in

Before disabling root login, confirm a normal account can become root. Run sudo whoami as that user:

bash
# As your normal user, prove sudo works BEFORE disabling root:
sudo whoami        # should print: root

If that prints root, you are safe to proceed. If it does not, grant sudo first and re-test.

Disable root login over SSH

This is the one that matters most, because SSH is the internet-facing door. In /etc/ssh/sshd_config (or a drop-in under /etc/ssh/sshd_config.d/):

code
PermitRootLogin no

Check and reload without dropping your session:

bash
sudo sshd -t                       # validate config
sudo systemctl reload ssh          # or: reload sshd

Keep your current session open and confirm a fresh ssh youruser@server still works before closing it. (On Debian and Ubuntu the service unit is ssh; on RHEL and Fedora it is sshd.) PermitRootLogin takes four values: no blocks root entirely, prohibit-password blocks root password logins but still allows a root SSH key (useful for some automation), forced-commands-only allows a root key only to run a pre-set command, and yes is the permissive setting you are removing.

Lock the root password (console too)

Disabling SSH root login does not touch console or su access. To stop anyone from su - into root with a password, lock the root password:

bash
sudo passwd -l root

This puts a ! in the hash so no password matches. You still become root through sudo (which does not use the root password), so your day-to-day workflow keeps working. To check: sudo passwd -S root shows L.

There is one real caveat, and it is the one people get bitten by. Locking the root password changes how emergency recovery behaves. If the box later fails to boot and drops into rescue or emergency mode, systemd runs sulogin, which asks for the root password, and a locked password makes it refuse outright:

code
Cannot open access to console, the root account is locked.
See sulogin(8) man page for more details.

You are not stuck, but you have to plan the way back in before you need it. Either keep a recovery path that does not go through sulogin (interrupt the bootloader and boot with init=/bin/bash, or rd.break, or a rescue ISO), or tell systemd to hand out a passwordless rescue shell:

bash
sudo systemctl edit rescue.service       # add under [Service]:
# Environment=SYSTEMD_SULOGIN_FORCE=1
sudo systemctl edit emergency.service    # same line

For a one-off you can pass it on the kernel command line instead: add systemd.setenv=SYSTEMD_SULOGIN_FORCE=1 (with rescue) at the bootloader. That option trades the lockout for a passwordless root shell at the physical console, so only set it on machines whose console is physically protected.

What you do NOT want

Do not delete the root account or set its shell to nologin blindly: many system tools and recovery paths expect root to exist. Locking the password and disabling SSH root login achieves the security goal while keeping the account intact for sudo. Just remember the recovery caveat above: a locked root password also locks the default sulogin rescue prompt, so set up an alternative recovery path (or SYSTEMD_SULOGIN_FORCE=1) before you rely on it.

Disable SSH password authentication

Password authentication is the surface that brute-force bots hammer all day. Once your key is installed on the server and you have confirmed it works, turn passwords off and the whole attack class disappears. It pairs naturally with PermitRootLogin no, so I put both in one drop-in, for example /etc/ssh/sshd_config.d/99-hardening.conf on modern distros (or straight into /etc/ssh/sshd_config):

code
# Keys only, no passwords
PasswordAuthentication no
KbdInteractiveAuthentication no
PubkeyAuthentication yes

# No direct root login
PermitRootLogin no

KbdInteractiveAuthentication no matters: on some systems a password can still be entered through the keyboard-interactive path even after PasswordAuthentication no, so disable both. Once this is live, anyone without an installed key gets Permission denied (publickey), because a key is the only method the server still offers.

Apply it without locking yourself out

This is the part people get wrong. Before you cut over, prove key auth works, and keep a second session open. Editing /etc/ssh and reloading the daemon are root tasks, so those steps use sudo; the login test runs as your normal user:

bash
# 1. In a SECOND terminal, confirm you can log in with your key right now.
ssh user@server

# 2. Check the config for syntax errors before reloading.
sudo sshd -t

# 3. Reload (does not drop existing sessions).
sudo systemctl reload ssh   # or: sudo systemctl reload sshd

Keep your existing session open until a brand-new connection succeeds. If something is wrong, you still have the open session to fix it. sshd -t catches typos before they take the service down. A reload is enough for a config change and does not drop existing connections; a full restart also works but is unnecessary.

Worth adding while you are here

code
# Don't wait forever on a half-open login
LoginGraceTime 20

# Optional: restrict who can log in at all
AllowUsers deploy ishan

Resist the urge to change the port for "security." Moving off 22 cuts log noise but is not a real control; a scanner finds the new port in seconds. Keys-only plus no-root is what actually matters. If you want fewer logs, a tool like fail2ban is more honest than security-through-obscurity. To check the result, audit the daemon's algorithms.

Scan and audit your SSH configuration

Locking down logins is half the job; the other half is the cryptography the daemon is willing to negotiate. ssh_scan is Mozilla's SSH configuration and policy scanner. It connects to a host, reads the key-exchange, host-key, cipher and MAC algorithms the daemon advertises in its handshake, and prints a JSON report of what it found and where that fails Mozilla's "Modern" OpenSSH policy. It never logs in; it only inspects the negotiation.

One caveat up front: Mozilla archived the project on 24 January 2022. The last release was v0.0.44 in May 2021. It still runs, but the bundled policy is frozen at 2021's idea of "modern," so treat its verdict as a starting point. Maintained alternatives are at the end of this section.

Install and run it

The gem is the canonical install; the Docker image keeps an unmaintained Ruby gem off your machine (and sidesteps dependency fuss on Ruby 3.x):

bash
gem install ssh_scan
ssh_scan -t ssh.example.com

# or, contained:
docker run --rm -it mozilla/ssh_scan -t ssh.example.com

Read the report

A scan against a host running an older OpenSSH looks like this (algorithm arrays trimmed for readability; the real output lists every offered algorithm):

json
{
  "ssh_scan_version": "0.0.44",
  "ip": "192.168.1.1",
  "hostname": "",
  "port": 22,
  "server_banner": "SSH-2.0-OpenSSH_7.1p2 Debian-2",
  "ssh_version": 2.0,
  "os": "debian",
  "ssh_lib": "openssh",
  "key_algorithms": [
    "curve25519-sha256@libssh.org",
    "diffie-hellman-group14-sha1"
  ],
  "encryption_algorithms_server_to_client": [
    "chacha20-poly1305@openssh.com",
    "aes256-gcm@openssh.com"
  ],
  "mac_algorithms_server_to_client": [
    "hmac-sha2-512-etm@openssh.com",
    "hmac-sha1"
  ],
  "compliance": {
    "policy": "Mozilla Modern",
    "compliant": false,
    "recommendations": [
      "Remove these Key Exchange Algos: diffie-hellman-group14-sha1",
      "Remove these MAC Algos: umac-64-etm@openssh.com, hmac-sha1-etm@openssh.com, umac-64@openssh.com, hmac-sha1"
    ]
  }
}

The algorithm arrays are the raw facts (exactly what the daemon offered); the compliance block is the tool's opinion. Here the server offers modern primitives but still advertises diffie-hellman-group14-sha1 and hmac-sha1, so it fails. The recommendations only ever say "remove these": ssh_scan flags weak algorithms on the menu, never the absence of strong ones, so a pass is a floor, not proof of a hardened config.

An ssh_scan JSON report against a current OpenSSH 9.6p1 server, showing the compliance block with policy Mozilla Modern, compliant false, recommendations to remove several algorithms, and an overall grade of D
A real ssh_scan run against a current OpenSSH 9.6 scores grade D: the frozen 2021 policy even lists the post-quantum sntrup761x25519 key exchange under 'remove'. A reminder the archived policy is a starting point, not gospel.

Turn a finding into an sshd_config change

Pin explicit allow-lists in /etc/ssh/sshd_config that drop the flagged entries, rather than blocklisting weak algorithms one at a time:

code
KexAlgorithms curve25519-sha256@libssh.org,diffie-hellman-group-exchange-sha256
MACs hmac-sha2-512-etm@openssh.com,hmac-sha2-256-etm@openssh.com
Ciphers chacha20-poly1305@openssh.com,aes256-gcm@openssh.com,aes256-ctr

Validate and reload exactly as above (sudo sshd -t && sudo systemctl reload ssh, or sshd on RHEL and Fedora), then re-run the scan and confirm "compliant": true. That edit-scan-reload loop is the point of the tool.

Useful flags and a custom policy

FlagWhat it does
-t, --targetThe IP, hostname, or CIDR range to scan. Repeatable.
-f, --fileRead targets from a file, one per line, for bulk scans.
-p, --portSSH port (default 22).
-P, --policyPath to a custom policy file (YAML) instead of Mozilla Modern.
-o, --outputWrite the JSON report to a file instead of stdout.
-T, --timeoutPer-connection timeout in seconds.
--threadsWorker threads for multi-host scans (default 5).
-V, --verbosityLogging level (INFO, DEBUG, etc.).
bash
ssh_scan -f hosts.txt -o ssh-audit-report.json --threads 10

Because the bundled policy is frozen, the most durable way to use the tool today is your own short allow-list, passed with -P (ssh_scan -t ssh.example.com -P house-policy.yml). Anything the server offers that is not on the list lands in recommendations:

yaml
name: "House SSH policy"
kex:
  - curve25519-sha256@libssh.org
  - diffie-hellman-group-exchange-sha256
macs:
  - hmac-sha2-512-etm@openssh.com
  - hmac-sha2-256-etm@openssh.com
encryption:
  - chacha20-poly1305@openssh.com
  - aes256-gcm@openssh.com
compression:
  - none

When to use something else

On a box you can already log into, OpenSSH itself tells you what the daemon supports and what it is configured to offer, no third-party tool needed:

bash
ssh -Q kex          # key-exchange algorithms this OpenSSH knows
sudo sshd -T | grep -iE 'kex|cipher|macs'   # what THIS daemon is configured to offer

For an actively maintained remote scanner, ssh-audit covers the same ground and more: it grades algorithms, flags known CVEs against the detected OpenSSH version, and notes missing strong algorithms. If I were scripting this into CI fresh in 2026, that is what I would use.

ToolMaintainedBest for
ssh_scanNo (archived 2022)Quick remote read of offered algorithms; legacy pipelines that already parse its JSON
ssh-auditYesModern remote audits: grades, CVE flags, missing-strong-algorithm warnings
ssh -Q + sshd -TYes (ships with OpenSSH)Local checks on a box you already control, zero dependencies

SSH login banner before authentication

To show a message before someone authenticates over SSH, point the Banner directive in sshd_config at a file. The part people get wrong is which file does this: /etc/motd prints after you log in, the Banner file prints before authentication. If the goal is a legal "authorized use only" notice that an attacker sees before they are in, you want Banner, not motd.

Set it up

Three steps: write the banner text, register it, reload the daemon. Keep the text plain ASCII; the banner is sent raw to the client's terminal before any session exists, so fancy escape sequences are a bad idea. Writing under /etc/ssh needs root:

bash
sudo tee /etc/ssh/banner.txt > /dev/null <<'EOF'
***************************************************************************
                            AUTHORIZED ACCESS ONLY
  This system is restricted to authorized users. All activity is logged
  and monitored. Unauthorized access is prohibited and will be prosecuted.
***************************************************************************
EOF

Then point sshd at it. Edit /etc/ssh/sshd_config and add (or uncomment) the line:

bash
Banner /etc/ssh/banner.txt

The default is Banner none, which is why a stock server shows nothing before the prompt. Always give an absolute path; relative paths are not resolved against anything useful.

I used /etc/ssh/banner.txt here, but the traditional file for a pre-login message is /etc/issue.net, and plenty of guides point Banner at that. Either works; Banner does not care what the file is called. The one thing to know is that /etc/issue.net is also consumed by the local login stack for console logins, so if you only want the text on SSH connections, a dedicated file keeps the two concerns separate. Validate with sudo sshd -t and reload exactly as in the previous section.

Connect and the banner lands before authentication. This transcript is from a server that still accepts passwords, so the banner sits just above the password prompt. On the keys-only setup from the previous section there is no password prompt: the same banner prints first, then your key logs you in (or a client with no installed key gets Permission denied (publickey), as in the screenshot below):

text
$ ssh techearl@server.example
***************************************************************************
                            AUTHORIZED ACCESS ONLY
  This system is restricted to authorized users. All activity is logged
  and monitored. Unauthorized access is prohibited and will be prosecuted.
***************************************************************************
techearl@server.example's password:

The banner is printed by the server during the SSH protocol's pre-auth phase, so it shows even on a connection that then fails authentication. That is the point of it: a notice delivered to anyone who reaches the daemon, before they prove who they are.

An SSH connection probed with PreferredAuthentications=none showing the AUTHORIZED ACCESS ONLY banner, followed by Permission denied, proving the banner is delivered before and independent of authentication
Probed with PreferredAuthentications=none (no credentials offered), the server still sends the banner, then denies access. Proof the banner reaches a client before it authenticates. Real output against a configured sshd.
Banner (sshd_config)/etc/motd
When it showsBefore authenticationAfter successful login
Configured in/etc/ssh/sshd_config (Banner /path)The file /etc/motd itself
Who controls itSSH daemonThe login/PAM stack (pam_motd)
Seen by failed loginsYesNo
Typical useLegal "authorized use only" noticeWelcome text, host info, update reminders
Applies toSSH connections onlyEvery login (SSH, console, etc.)

Plenty of hardened servers set both: a stern pre-auth banner and a quieter post-login motd. The same warning-notice idea shows up one layer down, too: you can customize the sudo lecture so a policy message lands the first time a user reaches for elevated privileges.

On the client side, the OpenSSH client prints the banner to stderr, so it shows up even when you run a non-interactive remote command (only stdout gets piped). The connecting user can suppress it locally with LogLevel QUIET in their ~/.ssh/config. Treat the banner as a notice you are presenting, not something you can guarantee a remote script reads.

Per-group or per-source banners with Match

For a different banner per source address, user, or group, wrap a second Banner in a Match block. Match blocks live at the end of sshd_config, since everything after a Match line belongs to that conditional until the next Match or end of file:

bash
Banner /etc/ssh/banner.txt

Match Address 10.0.0.0/8
    Banner /etc/ssh/banner-internal.txt

Connections from 10.0.0.0/8 get the internal banner; everyone else gets the default. The same works with Match User, Match Group, and so on. Keep the global Banner line above the first Match so it acts as the fallback.

  • It leaks to anyone who can reach the port. Port scanners, bots, and curious strangers all see it. Do not put hostnames, OS versions, internal IPs, or contact names in it. "Authorized access only" is fine; "prod-db-03 running Ubuntu 22.04, call Dave at..." is an information disclosure.
  • It does not stop anyone. A banner is a legal and policy device, not a security control. The real hardening is the root and password lockdown above.
  • Cloud images sometimes pre-set it. Some AWS, GCP, and Azure base images ship a Banner or a dynamic motd already. Check what is there before adding your own so you do not end up with two notices stacked.
  • Keep it ASCII and short. UTF-8 box-drawing can render as garbage on minimal clients; long banners just annoy the humans who log in fifty times a day.
  • File-transfer tools discard it. The server still sends the banner, but sftp and scp clients typically suppress or ignore it, so do not rely on it surfacing in an automated transfer.

If the box is your own laptop or a single-user dev VM, a pre-auth banner is just noise you scroll past. Banners earn their place on shared, internet-facing, or compliance-scoped servers, the ones where "a notice said access was restricted" is a sentence someone might actually need to say later.

FAQ

Only if you have no other way to become root. Before disabling it, confirm a normal account can sudo whoami and get root. Keep your current session open while you reload sshd and test a fresh login. With a working sudo account, you are safe.

no blocks all root logins over SSH. prohibit-password blocks root password logins but still allows root via an SSH key, which some automation needs. For most servers, no plus a sudo-capable user is the right choice.

Yes, with sudo passwd -l root. Disabling SSH root login does not stop console or su access with the root password. Locking the password closes those while leaving the account usable through sudo, which does not rely on the root password.

It changes it, and this is the part people miss. If the system drops into rescue or emergency mode, systemd runs sulogin, which asks for the root password, and a locked password makes it refuse with Cannot open access to console, the root account is locked.

You can still recover. Pick one of these before you lock the password, not during an outage:

  • Interrupt the bootloader and boot with init=/bin/bash or rd.break.
  • Boot from a rescue ISO.
  • Set SYSTEMD_SULOGIN_FORCE=1 on rescue.service and emergency.service so systemd hands out a passwordless root shell at the console. Only do this on machines whose console is physically protected.

That is PAM's pam_access rule file, and it is a good complementary control. It restricts which accounts may log in and from where (tty, host, network), independent of the SSH config or the password lock.

Disabling SSH root login plus locking the password covers the common case. Reach for access.conf when you want finer rules, like allowing a given account only from the console or a specific subnet.

Skip it on a modern system. /etc/securetty and pam_securetty were the old way to limit root to specific terminals, but the model is largely obsolete: Red Hat disabled securetty by default in RHEL 8, and on current Debian and Ubuntu the file is usually absent (you will see Couldn't open /etc/securetty if something still references it). Use PermitRootLogin no for SSH, lock the password to close console and su, and reach for access.conf if you need per-tty rules.

Only if key authentication is not working yet. Always confirm ssh user@server logs you in with your key first, run sudo sshd -t to check the config, and keep a second session open during the reload. If a fresh connection works, you are safe.

It reduces automated log noise but is not a security control on its own; a scanner finds the new port in seconds. Keys-only authentication and disabling root login are the changes that actually reduce risk. Add fail2ban if the logs bother you.

Common causes: you set a relative path instead of an absolute one, you forgot to reload the daemon, or the file is unreadable by sshd. The connecting client can also suppress the banner with LogLevel QUIET in its own config, and some file-transfer tools (sftp, scp) discard it.

Either works. The Banner directive points at whatever absolute path you give it. The difference: /etc/issue.net is also read by the local login stack for console logins, so a dedicated file like /etc/ssh/banner.txt keeps the SSH notice separate from console messaging.

No. It connects only far enough to complete the algorithm-negotiation phase of the SSH handshake, reads the algorithms the daemon advertises, then disconnects. It never authenticates, so it needs no credentials and leaves no login in the auth log (though the connection attempt itself may be logged).

Use ssh-audit for anything new. It is actively maintained, grades each algorithm, flags known CVEs against the detected OpenSSH version, and warns when strong algorithms are missing, none of which ssh_scan does (Mozilla archived ssh_scan in January 2022). Reach for ssh_scan only when an existing pipeline already parses its JSON, or for a quick read against a custom YAML policy.

See also

Sources

Authoritative references this article was fact-checked against.

TagsLinuxrootsudoSSHsshd_configSecurityHardeningLogin Bannerssh_scan

Found this useful? Pass it on.

Copied

Ishan Karunaratne

Systems and Network Architect · Chief Technology Officer

Systems and network architect and Chief Technology Officer with more than two decades designing, building, and running production software, cloud and network architecture, Linux systems, and the bare metal underneath them, and lately working AI into the stack. A US Army veteran who served in Operation Iraqi Freedom. What I write here is drawn from the full arc of that work, across architecture, engineering, and operations, not any single job.

Keep reading

Related posts

Schedule a cron job on Linux with crontab: the five-field schedule, PATH and day-of-week gotchas, and WordPress WP-Cron driven by a real system cron.

How to Schedule a Cron Job on Linux

Schedule a recurring task on Linux with cron: open your crontab, write the five-field schedule, point it at a command, and avoid the environment and day-of-week traps. Plus WordPress scheduling with WP-Cron and a real crontab.

Grant sudo via the sudo or wheel group, edit sudoers safely with visudo, scope NOPASSWD rules, run commands as another user, and set the sudo lecture.

How to Give a User sudo Access on Linux

Grant sudo by adding a user to the sudo or wheel group or with a sudoers drop-in, edit sudoers safely with visudo, scope rules and NOPASSWD to specific commands, run commands as another user, and customize the sudo lecture.

Discard local changes in Git with restore and clean, then undo the last commit, pick reset or revert, untrack a file, and recover commits with reflog.

How to Discard Local Changes in Git

Discard local changes in Git with restore, checkout, and clean. Throw away edits to tracked files, delete untracked files, reset to the last commit, then undo a commit, choose reset or revert, untrack a file, and recover lost commits with reflog.