DEV Community

Praveen Kumar K
Praveen Kumar K

Posted on

Enable Password-Based SSH Authentication for Root User on EC2 Instances Using Userdata Script

πŸ“Œ 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):

  1. πŸ›‘ Stop your EC2 instance
  2. βš™οΈ Actions β†’ Instance Settings β†’ Edit User Data
  3. πŸ“‹ Paste the script
  4. ▢️ Start your instance
  5. πŸ–₯️ Actions β†’ Monitor and troubleshoot β†’ EC2 Serial Console
  6. πŸ”‘ 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 "=========================================="
--//--
Enter fullscreen mode Exit fullscreen mode

Top comments (0)