π Userdata Script: Enable Password-Based SSH Authentication for Root User
π Default Credentials:
- Username:
root - Password:
password123
β οΈ Change PASSWORD="password123" in the script to set your own password.
π This script runs on every instance start/stop, not just initial launch.
π Recovery Method (Lost Access to EC2 Instance):
- π Stop your EC2 instance
- βοΈ Actions β Instance Settings β Edit User Data
- π Paste the script
- βΆοΈ Start your instance
- π₯οΈ Actions β Monitor and troubleshoot β EC2 Serial Console
- π Login with
root/password123
β Supported OS:
Linux
β οΈ Security Warning: This script executes every time your instance starts/stops. After troubleshooting, make sure to remove this userdata and revert the changes.
Content-Type: multipart/mixed; boundary="//"
MIME-Version: 1.0
--//
Content-Type: text/cloud-config; charset="us-ascii"
MIME-Version: 1.0
Content-Transfer-Encoding: 7bit
Content-Disposition: attachment;
filename="cloud-config.txt"
#cloud-config
cloud_final_modules:
- [scripts-user, always]
--//
Content-Type: text/x-shellscript; charset="us-ascii"
MIME-Version: 1.0
Content-Transfer-Encoding: 7bit
Content-Disposition: attachment; filename="userdata.txt"
#!/bin/bash
#==============================================================================
# Script: Enable Password Authentication and Root Login for SSH
# Description: This script enables password-based authentication and root login
# for SSH by modifying sshd_config and files in sshd_config.d folder
# - Main file: Updates or adds keywords if not exist
# - .d folder files: Only comments out if keyword exists with "no"
# - Creates user and adds sudoers entry
#==============================================================================
# Define the main sshd_config file and the .d directory
SSHD_CONFIG="/etc/ssh/sshd_config"
SSHD_CONFIG_DIR="/etc/ssh/sshd_config.d"
#==============================================================================
# Function to update or add SSH configuration parameters (for main file only)
#==============================================================================
update_ssh_config() {
local file="$1"
local keyword="$2"
local value="$3"
if grep -qE "^#*${keyword}" "$file"; then
# Keyword exists (commented or uncommented), so replace it
echo "Updating existing ${keyword} in ${file}..."
sed -i "s/^#*${keyword}.*/${keyword} ${value}/" "$file"
else
# Keyword does not exist, so add it to the file
echo "Adding ${keyword} to ${file}..."
echo "${keyword} ${value}" >> "$file"
fi
}
#==============================================================================
# Function to comment out keyword if it exists with "no" (for .d folder files)
#==============================================================================
comment_if_no() {
local file="$1"
local keyword="$2"
if grep -qE "^${keyword} no" "$file"; then
# Keyword exists with "no" value, so comment it out
echo "Commenting out ${keyword} no in ${file}..."
sed -i "s/^${keyword} no/#${keyword} no/" "$file"
elif grep -qE "^${keyword}" "$file"; then
# Keyword exists with other value, leave it as is
echo "${keyword} already exists with correct value in ${file}. Skipping..."
else
# Keyword does not exist, no action needed
echo "${keyword} not found in ${file}. No action needed."
fi
}
#==============================================================================
# Function to verify and add keyword if not verified (for main file only)
#==============================================================================
verify_and_fix() {
local file="$1"
local keyword="$2"
local value="$3"
if grep -qE "^${keyword} ${value}$" "$file"; then
echo "β VERIFIED: ${keyword} ${value} is correctly set in ${file}"
return 0
else
echo "β NOT VERIFIED: ${keyword} ${value} not found in ${file}"
echo " Attempting to fix by adding ${keyword} ${value} to ${file}..."
# Remove any existing entries (commented or uncommented) to avoid duplicates
sed -i "/^#*${keyword}/d" "$file"
# Add the keyword with correct value
echo "${keyword} ${value}" >> "$file"
# Verify again after fix
if grep -qE "^${keyword} ${value}$" "$file"; then
echo " β FIXED: ${keyword} ${value} successfully added to ${file}"
return 0
else
echo " β FAILED: Unable to add ${keyword} ${value} to ${file}"
return 1
fi
fi
}
#==============================================================================
# Function to add sudoers entry for user
#==============================================================================
add_sudoers_entry() {
local username="$1"
local sudoers_file="/etc/sudoers"
local sudoers_entry="${username} ALL=(ALL) ALL"
# Check if entry already exists in sudoers file
if grep -qE "^${username}\s+ALL=\(ALL\)\s+ALL" "$sudoers_file"; then
echo "β Sudoers entry for ${username} already exists. Skipping..."
else
echo "Adding sudoers entry for ${username}..."
echo "$sudoers_entry" >> "$sudoers_file"
# Verify entry was added
if grep -qE "^${username}\s+ALL=\(ALL\)\s+ALL" "$sudoers_file"; then
echo "β Sudoers entry for ${username} added successfully."
else
echo "β Failed to add sudoers entry for ${username}."
fi
fi
}
#==============================================================================
# Update main sshd_config file
#==============================================================================
echo "=========================================="
echo "Updating main sshd_config file..."
echo "=========================================="
# Check and update PasswordAuthentication
update_ssh_config "$SSHD_CONFIG" "PasswordAuthentication" "yes"
# Check and update PermitRootLogin
update_ssh_config "$SSHD_CONFIG" "PermitRootLogin" "yes"
#==============================================================================
# Loop through all files in sshd_config.d directory
# Only comment out if keyword exists with "no" value
# Do not add new keywords to these files
#==============================================================================
echo ""
echo "=========================================="
echo "Processing files in sshd_config.d directory..."
echo "(Only commenting out if keyword exists with 'no' value)"
echo "=========================================="
if [ -d "$SSHD_CONFIG_DIR" ]; then
for file in "$SSHD_CONFIG_DIR"/*.conf; do
if [ -f "$file" ]; then
echo ""
echo "Processing file: $file"
echo "------------------------------------------"
# Comment out PasswordAuthentication if it exists with "no"
comment_if_no "$file" "PasswordAuthentication"
# Comment out PermitRootLogin if it exists with "no"
comment_if_no "$file" "PermitRootLogin"
fi
done
else
echo "Directory $SSHD_CONFIG_DIR does not exist. Skipping..."
fi
#==============================================================================
# Verify Configuration Changes and Fix if Not Verified (Main file only)
#==============================================================================
echo ""
echo "=========================================="
echo "Verifying configuration changes (Main file only)..."
echo "=========================================="
echo ""
echo "Verifying main sshd_config file:"
echo "------------------------------------------"
verify_and_fix "$SSHD_CONFIG" "PasswordAuthentication" "yes"
verify_and_fix "$SSHD_CONFIG" "PermitRootLogin" "yes"
#==============================================================================
# Final Verification - Display Current Configuration
#==============================================================================
echo ""
echo "=========================================="
echo "Final Configuration Status:"
echo "=========================================="
echo ""
echo "Main sshd_config file ($SSHD_CONFIG):"
echo "------------------------------------------"
grep -E "^PasswordAuthentication|^PermitRootLogin" "$SSHD_CONFIG" || echo "No matching keywords found"
if [ -d "$SSHD_CONFIG_DIR" ]; then
echo ""
echo "Files in sshd_config.d directory:"
echo "------------------------------------------"
for file in "$SSHD_CONFIG_DIR"/*.conf; do
if [ -f "$file" ]; then
echo ""
echo "File: $file"
grep -E "PasswordAuthentication|PermitRootLogin" "$file" || echo "No matching keywords found"
fi
done
fi
#==============================================================================
# Restart SSH service
#==============================================================================
echo ""
echo "=========================================="
echo "Restarting SSH service..."
echo "=========================================="
systemctl restart sshd || service sshd restart
# Verify SSH service status
echo ""
echo "Verifying SSH service status..."
systemctl status sshd --no-pager
#==============================================================================
# User Creation Section
# TODO: Replace 'root' with your desired username
# TODO: Replace 'password123' with your desired password
#==============================================================================
echo ""
echo "=========================================="
echo "User Creation Section"
echo "=========================================="
# Define username and password (modify as needed)
USERNAME="root"
PASSWORD="password123"
# Create user
echo "Creating user: $USERNAME"
useradd "$USERNAME" 2>/dev/null || echo "User $USERNAME may already exist"
# Set password for the user
echo "$PASSWORD" | passwd --stdin "$USERNAME"
# Verify user creation
echo ""
echo "Verifying user creation..."
id "$USERNAME"
#==============================================================================
# Add Sudoers Entry for User (Not using wheel group)
#==============================================================================
echo ""
echo "=========================================="
echo "Adding Sudoers Entry for User"
echo "=========================================="
# Add sudoers entry for the user
add_sudoers_entry "$USERNAME"
# Verify sudoers entry
echo ""
echo "Verifying sudoers entry:"
echo "------------------------------------------"
grep -E "^${USERNAME}" /etc/sudoers && echo "β Sudoers entry verified successfully." || echo "β Sudoers entry not found."
echo ""
echo "=========================================="
echo "Script execution completed successfully!"
echo "=========================================="
--//--
Top comments (0)