Enhancing Linux System Security Through Practical Optimization Techniques
Command History Auditing
Enabling command history with timestamps and increasing the history size provides visibility into system operations. This helps track user activiites and troubleshoot issues:
# /etc/profile.d/history_config.sh
export HISTSIZE=10000
export HISTTIMEFORMAT="%Y-%m-%d %H:%M:%S $(whoami) "
The whoami command is preferred over $USER environment variable as it accurately reflects the effective user identity, even after su/sudo switches.
For advanced auditing, consider integrating rsyslog with Elasticsearch for centralized logging and analysis.
SSH Brute Force Protection
Automatically block IPs with repeated failed SSH attempts using this script:
#!/bin/bash
awk '/Failed password/{
if (match($11,/((25[0-5]|2[0-4]\d|1?\d?\d).?){4}/))
{ip[$11]++}
else
{ip[$13]++}
};
END{
for (i in ip){
if (ip[i] >= 10){
print i
}
}
}' /var/log/secure > ~/temp_ips.txt
while read -r ip; do
if ! iptables -nL | grep -q "$ip"; then
iptables -A INPUT -s "$ip" -j DROP
fi
done < ~/temp_ips.txt
rm ~/temp_ips.txt
Schedule this script via cron and reset rules daily:
*/5 * * * * /usr/local/bin/ssh_protect.sh
0 0 * * * iptables -F
Key-Based SSH Authentication
Disable password authentication and enforce key-based logins:
- Generate SSH keys:
ssh-keygen -t rsa -b 4096
- Copy public key to server:
ssh-copy-id user@server
- Configure SSH daemon:
# /etc/ssh/sshd_config
PasswordAuthentication no
PubkeyAuthentication yes
Restart SSH service after configuration changes.
System File Protection
Secure critical account files with immutable attribute:
chattr +i /etc/{passwd,shadow,group,gshadow}
This prevents unauthorized modifications to user account information.
Additional Security Measures
- Disable unnecessary services and ports
- Implement least privilege access controls
- Enforce strong pasword policies
- Regularly update system packages