On newly provisioned Linux cloud servers, the vast majority of images default to root account as the initial login entry point.root has unrestricted highest-level system-call privileges. Any mistyped file overwrite or incorrect rm -rf paths or unusual permission changes (such as chmod -R 777 /), can directly cause irreversible system crashes or data loss. Meanwhile, in an open public IPv4 environment, attacks targeting root SSH brute-force attacks and weak-password scans against this username never stop.
The first step toward sound operations practices is to create a regular administrative account with clear ownership, using sudo elevate privileges as needed to run privileged commands, then block, after validation is complete, root direct remote access channel.
1. Why Administrators Must Separate root Access from Everyday Operations#
Separating everyday operations from privileged execution provides core benefits in three engineering areas:
- Create an Operational Safety Margin: When regular users make system-level changes, they must explicitly prefix the command with
sudo. This creates a mental pause and an opportunity to review the command, preventing mistyped wildcards from damaging system files during routine directory changes, application configuration edits, or cache cleanup. - Command Auditing and Traceability: System logs (such as
/var/log/auth.logor/var/log/secureaccurately records everysudothe execution time of each invocation, the initiating user, the working directory, and the full command. When multiple engineers maintain a system together or unexpected changes occur, tracing the root cause is far easier than if everyone directly sharesrootthe terminal is clearer. - Reduce the Exposed Attack Surface: Disable
rootremote login, external scanners can no longer guess credentials using a fixed username. Attackers must identify both the specific administrator username and a strong key or password, greatly increasing the difficulty of intrusion.
Provider Default Environment Differences and Out-of-Band Recovery Channels#
Before changing any account or authentication settings, understand the server's current initial state and available emergency access methods:
- DMIT instance : DMIT system images use SSH key authentication by default during initialization, and their default security policy generallyDirectly Disable Remote root Password Login. To reset the password or update the public key, use the “Access” tab in the DMIT control panel. Note: under DMIT Docs rules, after changing an SSH key or password through the panel, you must reboot the instance there as instructed for the change to be written and take effect. DMIT also provides a web-based “Console,” a critical recovery entry point when configuration errors occur.
- BandwagonHost( BandwagonHost ) instance : BandwagonHost's authentication system is clearly separated into the client area billing password, KiwiVM management panel password, and operating system's
rootpasswords are independent. KiwiVM includes an Interactive Console and VNC, allowing direct access to the underlying Shell without a public SSH connection even if SSH is misconfigured, firewall rules block access, or network services fail.
Core Principle: when creating an administrative user, configuring public keys, and adjusting
sudoersthroughout the entire process,Do Not Close the Original root SSH Connection. Perform all validation from a new local terminal window on your computer. If authentication fails there, the original root session remains available to correct the problem immediately.
2. Prerequisites: Check for and Install sudo#
Minimal Images of different distributions trim the basic toolset to varying degrees. For example, a minimal Debian system deployed on BandwagonHost or DMIT may not have the following installed by default: sudo tool; Ubuntu includes it by default.
In the current root session, first check whether the system has sudo:
which sudoIf no binary path is returned, such as /usr/bin/sudo), install the missing components immediately from the operating system's official repositories:
Debian / Ubuntu Systems:
apt update && apt install -y sudoRocky Linux / AlmaLinux / CentOS / Fedora family:
dnf install -y sudoAfter Installation, Check the Version to Confirm the Component Is Fully Installed:
sudo -V | head -n 13. Create an Administrative User and Configure the Admin Group#
The group name used to grant administrative privileges differs between distributions:
- Debian / Ubuntu: The default privilege-elevation group is
sudogroup. - Rocky Linux / AlmaLinux / RHEL: The default privilege-elevation group is
wheelgroup.
to create one named deploy as the example administration account (replace it with an identifiable username that follows your team's conventions):
3.1 Create the User#
On Debian and Ubuntu, the recommended high-level interactive tool is adduser, it automatically creates the home directory and copies the skeleton configuration (/etc/skel) and interactively prompts you to set the user's password:
adduser deployOn Rocky Linux, AlmaLinux, or a minimal Debian installation, if only the low-level useradd command, specify parameters to create the home directory and login Shell:
useradd -m -s /bin/bash deploy
passwd deployPay Special Attention to What the sudo Password Actually Is: When the user runs
sudo <command>the system prompts by default for a password that is not the root password, butThe Regular User's Own Login Password. Even if passwordless SSH-key login is configured on a DMIT or BandwagonHost server, Linux's local PAM authentication module still relies on the user's password to validate sudo access. Therefore, you must usepasswdSet a strong, unique password for this account.
3.2 Add the User to the Privileged Administration Group#
add the user to the system's predefined administrative group. Be sure to use -aG(Append to Groups) parameter; if you omit -a Enter Only -G, the system will remove the user from all other existing supplementary groups, causing a permissions incident:
Debian / Ubuntu family (add to the sudo group):
usermod -aG sudo deployRocky Linux / AlmaLinux Systems (Add to the wheel Group):
usermod -aG wheel deployCheck the User's UID, GID, and Group Membership:
id deployNormal output should look like this:
uid=1001(deploy) gid=1001(deploy) groups=1001(deploy),27(sudo)4. Deploy SSH Key Authentication for the New User#
Production environments should not expose password-based authentication on SSH ports. Since environments such as DMIT commonly use public-key authentication, install your local computer's SSH public key in the new user's home directory.
4.1 Standard Initialization .ssh Directory Structure#
The SSH server checks permissions on related files and directories very strictly. If permissions are too broad,sshd StrictModes mechanism automatically rejects the connection.
In the root terminal where you are already logged in, securely create the new user's key directory and credential storage file:
mkdir -p /home/deploy/.ssh
touch /home/deploy/.ssh/authorized_keysTake the public key generated on your local development machine (usually ~/.ssh/id_ed25519.pub or ~/.ssh/id_rsa.pub single-line text) into this file. Open it in a text editor to enter the content:
nano /home/deploy/.ssh/authorized_keys4.2 Correct Ownership and File Permission Modes#
Because root created this file on the user's behalf, its initial owner is root:root, the regular user cannot read or append to it, causing the server to reject their login outright. Correct ownership and apply minimum required permissions immediately:
# 变更属主归还给新用户
chown -R deploy:deploy /home/deploy/.ssh
# 目录必须且只能由所有者读写执行(700)
chmod 700 /home/deploy/.ssh
# 密钥文件必须且只能由所有者读写(600)
chmod 600 /home/deploy/.ssh/authorized_keys4.3 Verify Login in Both Directions and Privilege Elevation#
On your local computer, open aA New Terminal(remember to keep the original root connection open), then connect as the newly created user:
ssh -p 22 deploy@你的服务器IPAfter connecting, run these verification commands step by step:
# 验证当前身份
whoami
# 输出应为:deploy
# 验证管理凭据缓存与提权状态(此时需输入 deploy 自身的密码)
sudo -v
# 验证能否成功获取 root 权限
sudo whoami
# 输出必须严格为:rootIf sudo whoami outputs root, confirming that the administrative user has been created and system-group permissions are fully in place.
5. Master sudo Rules and visudo Customization#
The administrative group grants full system administration privileges, equivalent to root. In complex architectures, however, fine-grained permissions are often needed, such as allowing a CI/CD account to restart Nginx without a password or developers to read system logs.
All sudo Rules Are Centralized In /etc/sudoers and /etc/sudoers.d/ directory.
5.1 Never Edit sudoers Directly with an Ordinary Text Editor#
/etc/sudoers files have a special syntax structure. If someone uses vim、nano or similar tools and accidentally add a typo or semicolon, after saving and exiting the entire system's sudo will fail immediately, leaving all non-root users unable to elevate privileges again.
Use the Dedicated Validation Tool When Editing Rules:
sudo visudovisudo On saving, it performs an atomic syntax check of the modified content. If there is a syntax error, it blocks the exit process and identifies the exact line so the administrator can fix it. The changes are written to disk only when the syntax is fully valid.
To validate the syntax of the current rules after deploying a script without entering interactive mode, run:
sudo visudo -c5.2 Recommended Modular Configuration:/etc/sudoers.d/#
Do Not Put All Custom Rules into the Main File /etc/sudoers within. Best practice is to, in /etc/sudoers.d/ create separate files in the directory for specific services or accounts.
Requirements:
- File permissions within the directory must be
0440(r--r-----)。 - Filenamecannot use
.at the beginning, and must not contain~or., otherwisesudowill ignore this configuration file outright, as required by the system's default ignore rules.
For example, configure a rule allowing an automated deployment account to restart a specific service without a password:
sudo visudo -f /etc/sudoers.d/90-deploy-servicesIn the editor that opens, follow the standard syntax:
# 语法构成:
# 谁(用户或组) 主机=(运行身份:运行组) [选项] 允许执行的程序路径
# 示例 1:允许 deploy 用户免密管理网络与系统服务(适合特定编排运维)
deploy ALL=(ALL) NOPASSWD: /usr/bin/systemctl restart nginx, /usr/bin/systemctl reload nginx
# 示例 2:全量免密提权(常用于自动化流水线,但对个人账户应极其审慎)
# deploy ALL=(ALL) NOPASSWD: ALL5.3 Check Effective Permissions#
Under any user account, you can check your permissions instead of guessing by running:
sudo -lThe system lists each environmental restriction matching the current user (Matching Defaults entries) and the specific commands they are explicitly authorized to run.
5.4 Beware of Seemingly Safe Privilege-Escalation Traps#
For convenience, many administrators will, in sudoers to allow seemingly harmless commands, but without security precautions, ordinary users may bypass restrictions and obtain full root access:
- Editor Pitfalls: grants the user
sudo /usr/bin/vim /etc/nginx/nginx.confprivileges, the user only needs to enter the following in vim::!/bin/bashor:sh, immediately opening a root Shell without a password. To grant editing permissions, usesudoedit. - Wildcard and Directory Write-Permission Pitfalls: If you authorize
sudo /opt/scripts/*.sh, while/opt/scriptsthe directory or scripts inside it are owned bydeploythemselves, that user can modify the script to add arbitrary malicious commands and then usesudoexecution is effectively equivalent to unrestricted root access. - High-Risk Privilege Escalation Through Binaries: such as
find、awk、lessand other system tools with native Shell execution capabilities must never be casually added to a passwordless privilege-escalation list.
6. Reduce the Attack Surface: Safely Disable Remote SSH Access for root#
Once the new administrative user is confirmed to reliably execute ssh and sudo afterward, completely disable public-network access for the following in the SSH daemon: root access.
6.1 Modify the SSH Server Configuration#
Edit the main configuration file (or /etc/ssh/sshd_config.d/ the supplementary configurations under it):
sudo nano /etc/ssh/sshd_configLocate and ensure the following key directives are active (remove the leading # comment):
# 彻底禁止 root 用户通过 SSH 协议登录
PermitRootLogin no
# 强制仅允许密钥登录,全面关闭密码认证(视团队情况,建议开启以消除暴力破解)
PasswordAuthentication no6.2 Syntax Validation and Graceful Reloading#
Before Restarting the Service, Check the SSH Configuration Syntax:
sudo sshd -tIf no errors are printed, the configuration is safe. Gracefully reload the SSH process:
sudo systemctl reload sshdNote:
systemctl reloadapplies only the new configuration and never interrupts currently active SSH sessions.
6.3 Recovery Plans and Troubleshooting Lost Connectivity#
If a configuration mistake, such as pasting the wrong public key, reversing permissions, or accidentally disabling all authentication methods, locks you out of a newly opened terminal, do not panic. Recover using the underlying mechanisms of the two providers described earlier:
- BandwagonHost Users: Open the KiwiVM control panel and select “Interactive Console” or “Root shell - basic” in the left navigation. This out-of-band terminal connects directly at the virtualization layer and is unaffected by SSH service status. Use the initial system root password to enter the terminal and modify
/etc/ssh/sshd_configwillPermitRootLogintemporarily change it back toyesand restartsshd. - DMIT Users: open the instance list in the client area, find the affected VM, and click “Console” to enter the web rescue page. Enter the root credentials to access the underlying system. If password login is disabled and prevents access, first reset the credentials through “Access” in the DMIT panel, reboot through the panel as required, then log into the console to make repairs.
7. Account Lifecycle: Access Revocation and Deletion#
After staffing changes or a completed project handover, permissions must be revoked thoroughly and in a controlled manner. Be clear that:Revoking sudo Privileges, Terminating Active Sessions, and Deleting an Account Are Three Completely Separate Stages.
7.1 Revoke a User's Administrative Privileges (Demotion)#
Simply remove the user from the privileged group; their regular-user functions and data remain completely unaffected:
Debian / Ubuntu Systems:
sudo deluser deploy sudoRocky Linux / AlmaLinux family:
sudo gpasswd -d deploy wheelIf this user, in /etc/sudoers.d/ contains a dedicated configuration file, remember to delete it as well:
sudo rm -f /etc/sudoers.d/90-deploy-*7.2 Revoke SSH Credentials and Lock the Account#
If an employee leaves or loses a device, first prevent further network authentication and immediately terminate existing connections:
# 清空用户的授权公钥
sudo truncate -s 0 /home/deploy/.ssh/authorized_keys
# 锁定用户密码(阻止一切密码验证形式)
sudo usermod -L deploy
# 强制杀死属于该用户的所有存活进程与 SSH 建立的会话连接
sudo pkill -u deploy7.3 Carefully and Completely Delete an Account#
Before final deletion, confirm that the user no longer owns any running systemd daemons, Nginx static resources, or critical database backups:
# 检查该用户是否有名下的定时任务
sudo crontab -u deploy -l
# 删除账户,并连带清理其家目录(-r / --remove-home)
sudo userdel -r deployWarning: if the account's home directory contains a website's working directory or a code repository, do not use
-rparameter; first transfer ownership of important business files usingchown -Rtransfer ownership to the new runtime user, such aswww-dataor another administrator), then remove obsolete account metadata after confirming everything is correct.