Limited Time Offer!
For Less Than the Cost of a Starbucks Coffee, Access All DevOpsSchool Videos on YouTube Unlimitedly.
Master DevOps, SRE, DevSecOps Skills!
Securing a Linux server requires a deep understanding of essential commands that help mitigate vulnerabilities, manage user access, and enforce system integrity. Here’s a comprehensive list of the top 50 Linux commands for securing a Linux server, organized into categories for better readability. Iโll cover each command with an explanation of its purpose and usage to give you an in-depth guide on securing your server.
User Management and Access Control
adduser
- Creates a new user account with a home directory and initial configurations. Run
adduser [username]
.
- Creates a new user account with a home directory and initial configurations. Run
usermod
- Modifies a user account. Useful for changing user groups, shell, and other settings:
usermod -aG [group] [username]
.
- Modifies a user account. Useful for changing user groups, shell, and other settings:
passwd
- Changes user passwords. It can also set password expiration policies with options like
-e
(expire):passwd [username]
.
- Changes user passwords. It can also set password expiration policies with options like
sudo
- Provides superuser privileges to a user. Control sudo permissions through the
/etc/sudoers
file for fine-grained access.
- Provides superuser privileges to a user. Control sudo permissions through the
lastlog
- Displays the last login times of all users, useful for identifying suspicious logins.
who
- Shows who is currently logged into the system:
who -a
.
- Shows who is currently logged into the system:
chage
- Configures password aging policies for a user, enforcing periodic password changes:
chage -E [expire_date] [username]
.
- Configures password aging policies for a user, enforcing periodic password changes:
faillog
- Displays failed login attempts to monitor unauthorized access attempts:
faillog -u [username]
.
- Displays failed login attempts to monitor unauthorized access attempts:
Filesystem Permissions and Ownership
chmod
- Changes file or directory permissions:
chmod 700 [filename]
.
- Changes file or directory permissions:
chown
- Changes file or directory ownership:
chown user:group [filename]
.
- Changes file or directory ownership:
umask
- Sets default permissions for newly created files and directories. Use
umask 027
for more restrictive permissions.
- Sets default permissions for newly created files and directories. Use
lsattr
- Lists file attributes, useful for finding immutable or restricted files:
lsattr [filename]
.
- Lists file attributes, useful for finding immutable or restricted files:
chattr
- Changes file attributes to make files immutable (useful for critical system files):
chattr +i [filename]
.
- Changes file attributes to make files immutable (useful for critical system files):
find
- Searches for files with specific permissions, users, or groups:
find / -type f -perm 777
.
- Searches for files with specific permissions, users, or groups:
getfacl
- Views Access Control List (ACL) permissions for files:
getfacl [filename]
.
- Views Access Control List (ACL) permissions for files:
setfacl
- Sets ACLs for users or groups on files:
setfacl -m u:username:rwx [filename]
.
- Sets ACLs for users or groups on files:
Network Security
iptables
- Configures the firewall for packet filtering and traffic control:
iptables -A INPUT -p tcp --dport 22 -j ACCEPT
.
- Configures the firewall for packet filtering and traffic control:
firewalld
- Manages firewall rules dynamically. Use
firewall-cmd
to add/remove firewall rules:firewall-cmd --zone=public --add-port=22/tcp --permanent
.
- Manages firewall rules dynamically. Use
nmap
- Scans open ports on a network to detect vulnerabilities:
nmap -sS [target_ip]
.
- Scans open ports on a network to detect vulnerabilities:
netstat
- Displays network connections and listening ports:
netstat -tuln
.
- Displays network connections and listening ports:
ss
- A faster alternative to netstat for checking socket statistics:
ss -tuln
.
- A faster alternative to netstat for checking socket statistics:
tcpdump
- Captures network packets to monitor traffic:
tcpdump -i eth0
.
- Captures network packets to monitor traffic:
ufw
- Uncomplicated Firewall, simplifying iptables for common use:
ufw enable
.
- Uncomplicated Firewall, simplifying iptables for common use:
fail2ban
- Monitors log files for failed login attempts and blocks IP addresses. Configuration is in
/etc/fail2ban/jail.conf
.
- Monitors log files for failed login attempts and blocks IP addresses. Configuration is in
Process and Resource Monitoring
ps
- Lists active processes, essential for detecting unauthorized processes:
ps aux
.
- Lists active processes, essential for detecting unauthorized processes:
top
- Displays real-time resource usage, monitoring for unusual activity.
htop
- An enhanced version of top with a more user-friendly interface.
kill
- Terminates suspicious processes by their process ID (PID):
kill -9 [PID]
.
- Terminates suspicious processes by their process ID (PID):
lsof
- Lists open files and the processes using them:
lsof -i
.
- Lists open files and the processes using them:
strace
- Traces system calls of a process to identify vulnerabilities in real-time:
strace -p [PID]
.
- Traces system calls of a process to identify vulnerabilities in real-time:
Logging and Auditing
journalctl
- Views and manages systemd logs:
journalctl -u ssh.service
.
- Views and manages systemd logs:
logrotate
- Manages log rotation for various system logs, configured in
/etc/logrotate.conf
.
- Manages log rotation for various system logs, configured in
auditctl
- Configures auditing rules for monitoring file access or command execution. Useful for compliance and security.
ausearch
- Searches through audit logs for specific events:
ausearch -c '[command]'
.
- Searches through audit logs for specific events:
auditd
- A daemon that manages and logs events specified by auditctl rules.
cat /var/log/auth.log
- Reads the authentication log file, showing login attempts.
cat /var/log/syslog
- Reads the system log for broader logging information on errors and activities.
Security Updates and Maintenance
apt-get update && apt-get upgrade
- Installs security patches and updates on Debian-based systems.
yum update
- Updates packages for Red Hat-based systems.
unattended-upgrades
- Configures automatic updates to keep your system secure with critical patches.
rkhunter
- Scans for rootkits and other vulnerabilities on the system.
chkrootkit
- Another tool for rootkit detection:
chkrootkit
.
- Another tool for rootkit detection:
7. SSH Configuration
sshd_config
- Configures the SSH daemon. Secure it by editing
/etc/ssh/sshd_config
(e.g., disable root login withPermitRootLogin no
).
- Configures the SSH daemon. Secure it by editing
ssh-keygen
- Generates SSH key pairs for secure password-less authentication.
ssh-copy-id
- Installs public keys on remote hosts to allow key-based SSH login:
ssh-copy-id [user@host]
.
- Installs public keys on remote hosts to allow key-based SSH login:
scponly
- Restricts users to SCP/SFTP commands only, enhancing secure file transfers.
Disk and File Integrity Monitoring
aide
- A tool that checks for changes to files and directories, useful for integrity verification:
aide --check
.
- A tool that checks for changes to files and directories, useful for integrity verification:
tripwire
- Another file integrity checker that creates a snapshot of your systemโs filesystem.
md5sum
- Checksums files for data integrity verification.
sha256sum
- Similar to md5sum, but uses SHA-256 for a more secure hash:
sha256sum [filename]
.
- Similar to md5sum, but uses SHA-256 for a more secure hash:
What are the Tips for Linux Server Security?
1. Disable Unnecessary Services
Unused services are potential vulnerabilities, as each open service represents a possible entry point for attackers. By identifying and disabling unnecessary services, you reduce the system’s exposure to threats and conserve server resources. Begin by listing all active services and then decide which ones are essential to your server’s functions. For example, if you identify services like FTP that are not required, disabling them will help secure the system. After disabling a service, itโs best to stop it from running to prevent it from restarting until itโs genuinely needed.
2. Limit Sudo Access
The sudo privilege grants users elevated access to execute commands as a superuser, which can pose a security risk if widely distributed. By limiting sudo privileges to essential users only, you ensure a smaller attack surface and reduce the chances of accidental or malicious misuse. You can manage sudo access by editing the sudoers configuration file and defining permissions specific to each user or group. Additionally, itโs beneficial to assign users to a dedicated group with sudo access rather than granting it individually. This practice makes it easier to manage and audit privileges. Configuring sudo permissions for specific commands only adds another layer of security by allowing users to perform certain tasks without unrestricted access.
3. Regular Backups
Backups are essential to ensure data integrity and availability. In case of data loss, corruption, or a security breach, backups allow you to restore your system to its previous state, reducing downtime and data loss. Regular backups should ideally be automated to maintain consistency. Tools like rsync allow for incremental backups, meaning only modified files are updated, saving time and storage space. Setting up automated backup schedules with cron jobs enables your server to run backups at regular intervals, such as daily or weekly, based on your requirements. Itโs also beneficial to store backups offsite or in a secure cloud location, protecting them from potential local threats.
4. Limit Open Ports
Every open port on your server is a pathway for external connections, which could be exploited if not properly managed. By limiting open ports to only those that are essential, you significantly reduce the network attack surface. Regularly review open ports to ensure they align with your server’s purpose, and close any unnecessary ones. You can monitor open ports by listing network services and reviewing which ports are open. To secure your server, implement firewall rules to block or restrict access to specific ports. For instance, allowing only SSH traffic while blocking other unused ports makes your system less accessible to unauthorized users. Regularly review and update firewall rules to maintain a minimal and secure port configuration.
5. Check System Integrity
File integrity monitoring is crucial for detecting unauthorized changes to files and directories. Tools like AIDE (Advanced Intrusion Detection Environment) and Tripwire help monitor the filesystem by creating a baseline database that represents a known good state of critical files. By periodically comparing the current state of files with this baseline, you can detect and respond to unauthorized modifications or tampering, which is often an indication of malicious activity. Set up regular integrity checks with these tools to automatically scan your system and notify you of any discrepancies. This proactive approach ensures you quickly detect security issues that could otherwise go unnoticed.
Continuous Monitoring and Proactive Security
Maintaining a secure Linux server requires a continuous commitment to monitoring and updating security practices. Periodically audit user privileges, keep services and packages updated, and ensure your firewall and backup configurations are aligned with best practices. Centralized logging and monitoring solutions, such as Syslog servers or Security Information and Event Management (SIEM) systems, allow for effective, scalable, and comprehensive server security management. These tools help identify unusual patterns and system anomalies, enabling you to proactively respond to threats and safeguard your Linux server.