Actualiser miscellaneous/secure_ssh.sh

This commit is contained in:
Philippe Favre
2024-11-14 03:16:20 +01:00
parent 56142b79c8
commit 859a750be7

View File

@@ -1,7 +1,7 @@
#!/bin/bash
# This script is designed to configure the SSH server on a Linux system according to Mozilla's security best practices.
# Its main purpose is to enhance the security of SSH connections by enforcing modern encryption standards, disabling insecure protocols, and reducing potential attack vectors.
# It enhances the security of SSH connections by enforcing modern encryption standards, disabling insecure protocols, and restricting root access.
# The script backs up the original SSH configuration file, applies a new set of secure settings, and then restarts the SSH service to apply the changes.
# These settings include disabling password authentication, limiting access to strong ciphers and key exchange methods, and enhancing brute-force protection.
# These recommendations are based on Mozilla's guidelines, which can be found here: https://infosec.mozilla.org/guidelines/openssh
@@ -11,11 +11,28 @@
# After that, execute it with root privileges using: `sudo ./secure_ssh.sh`.
# The script will automatically apply the recommended configuration changes and restart the SSH service.
# Check if the script is run as root
if [[ "$EUID" -ne 0 ]]; then
echo "This script must be run as root. Please use sudo to execute it."
exit 1
fi
# Variables
SSHD_CONFIG="/etc/ssh/sshd_config"
BACKUP_FILE="${SSHD_CONFIG}_$(date +'%Y%m%d_%H%M%S').bak" # Backup with date and time
# Backup the old configuration
cp "$SSHD_CONFIG" "${SSHD_CONFIG}.bak"
# Backup the old configuration with a timestamp
cp "$SSHD_CONFIG" "$BACKUP_FILE"
# Ask user if they want to restrict SSH access to a single IP
read -p "Do you want to restrict SSH access to a single IP? (yes/no): " restrict_ip
if [[ "$restrict_ip" == "yes" ]]; then
read -p "Enter the IP address to allow SSH access: " allowed_ip
allow_users="AllowUsers *@${allowed_ip}"
else
allow_users="# AllowUsers configuration not set"
fi
# Modify the sshd_config file
cat <<EOL > "$SSHD_CONFIG"
@@ -41,9 +58,19 @@ PermitRootLogin no
# Strict connection policy
MaxAuthTries 3
LoginGraceTime 30
# Additional security recommendations
AllowTcpForwarding no
MaxSessions 2
LogLevel VERBOSE
ClientAliveInterval 300
ClientAliveCountMax 2
# IP restriction based on user input
$allow_users
EOL
# Restart the SSH service
systemctl restart sshd
echo "SSH configuration has been updated according to Mozilla's security recommendations."
echo "SSH configuration has been updated and backed up to $BACKUP_FILE according to Mozilla's security recommendations."