321 lines
12 KiB
Bash
321 lines
12 KiB
Bash
#!/bin/bash
|
|
|
|
# Enhanced logging configuration
|
|
LOG_DIR="/home/jelastic/add-sftp-user-addon/logs"
|
|
LOG_FILE="$LOG_DIR/script_output.log"
|
|
ERROR_LOG="$LOG_DIR/errors.log"
|
|
OPERATION_LOG="$LOG_DIR/operations.log"
|
|
DEBUG_LOG="$LOG_DIR/debug.log"
|
|
DEBUG=${4:-0} # Set to 1 to enable debug logging, controlled by 4th argument
|
|
SCRIPT_ID="$(date +%Y%m%d%H%M%S)-$$" # Unique ID for this script run (timestamp-PID)
|
|
|
|
# Ensure log directory exists with proper permissions
|
|
mkdir -p $LOG_DIR
|
|
chmod 755 $LOG_DIR
|
|
|
|
# Rotate logs if they exceed 10MB (10485760 bytes)
|
|
for log_file in $LOG_FILE $ERROR_LOG $OPERATION_LOG $DEBUG_LOG; do
|
|
if [[ -f "$log_file" && $(stat -c%s "$log_file" 2>/dev/null || echo 0) -gt 10485760 ]]; then
|
|
mv "$log_file" "$log_file.$(date +%Y%m%d%H%M%S).old"
|
|
touch "$log_file"
|
|
chmod 644 "$log_file"
|
|
fi
|
|
done
|
|
|
|
# Enhanced logging functions
|
|
log() {
|
|
local level=${1:-INFO}
|
|
local message=${2}
|
|
local timestamp=$(date +"%Y-%m-%d %H:%M:%S")
|
|
local formatted_message="[$SCRIPT_ID] $timestamp [$level] $message"
|
|
|
|
# Log to appropriate files based on level
|
|
echo "$formatted_message" | tee -a $LOG_FILE
|
|
|
|
# Also log to operation log for main operations
|
|
if [[ "$level" == "INFO" || "$level" == "SUCCESS" ]]; then
|
|
echo "$formatted_message" >> $OPERATION_LOG
|
|
fi
|
|
|
|
# Also log errors to dedicated error log
|
|
if [[ "$level" == "ERROR" || "$level" == "WARNING" ]]; then
|
|
echo "$formatted_message" >> $ERROR_LOG
|
|
fi
|
|
|
|
# Log debug messages to debug log if DEBUG mode is on
|
|
if [[ "$level" == "DEBUG" && "$DEBUG" -eq 1 ]]; then
|
|
echo "$formatted_message" >> $DEBUG_LOG
|
|
fi
|
|
}
|
|
|
|
log_error() {
|
|
log "ERROR" "$1"
|
|
}
|
|
|
|
log_warning() {
|
|
log "WARNING" "$1"
|
|
}
|
|
|
|
log_debug() {
|
|
if [ "$DEBUG" -eq 1 ]; then
|
|
log "DEBUG" "$1"
|
|
fi
|
|
}
|
|
|
|
log_success() {
|
|
log "SUCCESS" "$1"
|
|
}
|
|
|
|
# Log system information for debugging context
|
|
log_system_info() {
|
|
log_debug "============= SYSTEM INFORMATION ============="
|
|
log_debug "Operating System: $(cat /etc/os-release | grep PRETTY_NAME | cut -d= -f2 | tr -d '\"')"
|
|
log_debug "Kernel: $(uname -r)"
|
|
log_debug "SSH Version: $(ssh -V 2>&1)"
|
|
log_debug "SSH Config Status: $(systemctl status sshd | grep Active | awk '{print $2}')"
|
|
log_debug "Script Parameters: username=$USERNAME, ssh_enabled=$SSH_ENABLED"
|
|
log_debug "=============================================="
|
|
}
|
|
|
|
# Function to log command execution with result
|
|
log_cmd() {
|
|
local cmd="$1"
|
|
local cmd_desc="$2"
|
|
|
|
log_debug "Executing: $cmd_desc"
|
|
log_debug "Command: $cmd"
|
|
|
|
# Execute command and capture output and status
|
|
local output
|
|
output=$(eval "$cmd" 2>&1)
|
|
local status=$?
|
|
|
|
if [ $status -eq 0 ]; then
|
|
log_debug "Command succeeded: $cmd_desc"
|
|
if [ -n "$output" ]; then
|
|
log_debug "Output: $output"
|
|
fi
|
|
else
|
|
log_error "Command failed ($status): $cmd_desc"
|
|
log_error "Error output: $output"
|
|
fi
|
|
|
|
return $status
|
|
}
|
|
|
|
# Fix SFTP configuration for Jelastic Virtuozzo LLSMP
|
|
fix_sftp_config() {
|
|
log "Checking and fixing SSH configuration for SFTP access"
|
|
|
|
# Create a backup of the original config
|
|
log_cmd "cp /etc/ssh/sshd_config /etc/ssh/sshd_config.bak.$(date +%Y%m%d%H%M%S)" "Creating backup of original sshd_config"
|
|
|
|
# Fix the malformed SFTP subsystem line - using safer sed approach
|
|
if grep -q "Subsystemsftp" /etc/ssh/sshd_config; then
|
|
log "Fixing malformed SFTP subsystem configuration"
|
|
# Use a temporary file for safer editing
|
|
if log_cmd "sed 's|Subsystemsftp/usr/libexec/openssh/sftp-server|Subsystem sftp /usr/libexec/openssh/sftp-server|g' /etc/ssh/sshd_config > /etc/ssh/sshd_config.new" "Fixing malformed Subsystem line"; then
|
|
log_cmd "mv /etc/ssh/sshd_config.new /etc/ssh/sshd_config" "Applying fixed configuration"
|
|
log_success "Fixed malformed Subsystem line"
|
|
else
|
|
log_error "Failed to fix Subsystem line, reverting to backup"
|
|
log_cmd "cp /etc/ssh/sshd_config.bak.$(ls -t /etc/ssh/sshd_config.bak.* | head -1 | awk -F/ '{print $NF}') /etc/ssh/sshd_config" "Restoring backup"
|
|
fi
|
|
fi
|
|
|
|
# Enable password authentication globally if it's set to no
|
|
if grep -q "^PasswordAuthentication no" /etc/ssh/sshd_config; then
|
|
log "Enabling password authentication in SSH"
|
|
if log_cmd "sed 's/^PasswordAuthentication no/PasswordAuthentication yes/g' /etc/ssh/sshd_config > /etc/ssh/sshd_config.new" "Enabling password authentication"; then
|
|
log_cmd "mv /etc/ssh/sshd_config.new /etc/ssh/sshd_config" "Applying configuration with password authentication"
|
|
log_success "Enabled password authentication"
|
|
else
|
|
log_error "Failed to enable password authentication, reverting to backup"
|
|
log_cmd "cp /etc/ssh/sshd_config.bak.$(ls -t /etc/ssh/sshd_config.bak.* | head -1 | awk -F/ '{print $NF}') /etc/ssh/sshd_config" "Restoring backup"
|
|
fi
|
|
fi
|
|
|
|
# Remove any existing incomplete/duplicate Match Group sftpusers blocks
|
|
if grep -q "Match Group sftpusers" /etc/ssh/sshd_config; then
|
|
log "Removing existing Match Group sftpusers blocks to prevent duplicates"
|
|
# This complex sed pattern removes the Match Group sftpusers block completely
|
|
if log_cmd "sed '/^Match Group sftpusers/,/^Match\|^[[:space:]]*$/d' /etc/ssh/sshd_config > /etc/ssh/sshd_config.new" "Removing existing Match Group blocks"; then
|
|
log_cmd "mv /etc/ssh/sshd_config.new /etc/ssh/sshd_config" "Applying cleaned configuration"
|
|
log_success "Removed existing Match Group sftpusers blocks"
|
|
else
|
|
log_error "Failed to remove existing Match Group blocks, reverting to backup"
|
|
log_cmd "cp /etc/ssh/sshd_config.bak.$(ls -t /etc/ssh/sshd_config.bak.* | head -1 | awk -F/ '{print $NF}') /etc/ssh/sshd_config" "Restoring backup"
|
|
fi
|
|
fi
|
|
|
|
# Configure SFTP chroot jail cleanly at the end of the file
|
|
log "Adding fresh SFTP chroot configuration for sftpusers group"
|
|
cat >> /etc/ssh/sshd_config << EOF
|
|
|
|
# SFTP chroot configuration added by SFTP addon
|
|
Match Group sftpusers
|
|
ChrootDirectory /home/sftpusers/%u
|
|
ForceCommand internal-sftp
|
|
PasswordAuthentication yes
|
|
AllowTcpForwarding no
|
|
X11Forwarding no
|
|
EOF
|
|
|
|
# Remove duplicate lines and verify config
|
|
log "Cleaning up configuration file"
|
|
if log_cmd "awk '!seen[\$0]++' /etc/ssh/sshd_config > /etc/ssh/sshd_config.new" "Removing duplicate lines"; then
|
|
log_cmd "mv /etc/ssh/sshd_config.new /etc/ssh/sshd_config" "Applying deduplicated configuration"
|
|
log_success "Removed duplicate lines from configuration"
|
|
else
|
|
log_error "Failed to remove duplicate lines, reverting to backup"
|
|
log_cmd "cp /etc/ssh/sshd_config.bak.$(ls -t /etc/ssh/sshd_config.bak.* | head -1 | awk -F/ '{print $NF}') /etc/ssh/sshd_config" "Restoring backup"
|
|
fi
|
|
|
|
# Verify the configuration before restarting
|
|
log "Verifying SSH configuration before restart"
|
|
if log_cmd "sshd -t" "Validating sshd configuration"; then
|
|
log_success "SSH configuration is valid, restarting service"
|
|
log_cmd "systemctl restart sshd" "Restarting SSH service"
|
|
else
|
|
log_error "SSH configuration is INVALID, reverting to backup"
|
|
log_cmd "cp /etc/ssh/sshd_config.bak.$(ls -t /etc/ssh/sshd_config.bak.* | head -1 | awk -F/ '{print $NF}') /etc/ssh/sshd_config" "Restoring backup"
|
|
log "Restarting SSH with original configuration"
|
|
log_cmd "systemctl restart sshd" "Restarting SSH service with original config"
|
|
return 1
|
|
fi
|
|
|
|
return 0
|
|
}
|
|
|
|
validate_username() {
|
|
local username=$1
|
|
log_debug "Validating username: $username"
|
|
|
|
if ! [[ $username =~ ^[a-zA-Z0-9_]{3,32}$ ]]; then
|
|
log_error "Invalid username format. Username must be 3-32 characters long and contain only letters, numbers, and underscores."
|
|
return 1
|
|
fi
|
|
|
|
log_debug "Username validation passed"
|
|
return 0
|
|
}
|
|
|
|
USERNAME=$1
|
|
PASSWORD=$2
|
|
SSH_ENABLED=${3:-false}
|
|
|
|
log "======== STARTING SFTP USER SETUP ========"
|
|
log "Script started with username: $USERNAME, ssh_enabled: $SSH_ENABLED, script_id: $SCRIPT_ID"
|
|
|
|
# Log system information
|
|
log_system_info
|
|
|
|
# Fix SFTP configuration
|
|
log "Phase 1: Configuring SSH/SFTP service"
|
|
if ! fix_sftp_config; then
|
|
log_error "Failed to configure SSH/SFTP service, exiting"
|
|
exit 1
|
|
fi
|
|
log_success "SSH/SFTP service configuration completed"
|
|
|
|
# Validate username format
|
|
log "Phase 2: Validating username"
|
|
if ! validate_username "$USERNAME"; then
|
|
log_error "Username validation failed, exiting"
|
|
exit 1
|
|
fi
|
|
log_success "Username validation passed"
|
|
|
|
# Check if user already exists
|
|
log "Phase 3: Checking if user already exists"
|
|
if id "$USERNAME" &>/dev/null; then
|
|
log_error "Username $USERNAME already exists. Please choose a different username."
|
|
exit 1
|
|
fi
|
|
log_success "Username is available for creation"
|
|
|
|
USER_HOME="/home/sftpusers/$USERNAME"
|
|
ROOT_DIRECTORY="/var/www/webroot/ROOT"
|
|
log_debug "Setting paths - USER_HOME: $USER_HOME, ROOT_DIRECTORY: $ROOT_DIRECTORY"
|
|
|
|
# Create the sftpusers group if it doesn't exist
|
|
log "Phase 4: Setting up groups"
|
|
if ! getent group sftpusers > /dev/null; then
|
|
log "Creating sftpusers group for SFTP chroot access"
|
|
log_cmd "groupadd sftpusers" "Creating sftpusers group"
|
|
fi
|
|
log_success "Group setup completed"
|
|
|
|
# Ensure the parent directory for user home directories exists
|
|
log "Phase 5: Setting up directories"
|
|
if [ ! -d "/home/sftpusers" ]; then
|
|
log "Creating /home/sftpusers directory"
|
|
log_cmd "mkdir -p /home/sftpusers" "Creating /home/sftpusers directory"
|
|
log_cmd "chown root:root /home/sftpusers" "Setting ownership for /home/sftpusers"
|
|
log_cmd "chmod 755 /home/sftpusers" "Setting permissions for /home/sftpusers"
|
|
fi
|
|
log_success "Directory setup completed"
|
|
|
|
# Create the user account
|
|
log "Phase 6: Creating user account"
|
|
if [ "$SSH_ENABLED" = "true" ]; then
|
|
log "Creating user with SSH access"
|
|
log_cmd "useradd -d $USER_HOME -m -s /bin/bash $USERNAME" "Creating user with bash shell"
|
|
else
|
|
log "Creating user with SFTP-only access"
|
|
log_cmd "useradd -d $USER_HOME -m -s /sbin/nologin $USERNAME" "Creating user with nologin shell"
|
|
fi
|
|
log_success "User account created"
|
|
|
|
# Set password
|
|
log "Phase 7: Setting user password"
|
|
log_cmd "echo '$USERNAME:$PASSWORD' | chpasswd" "Setting user password"
|
|
log_success "Password set for user $USERNAME"
|
|
|
|
# Set up proper directory structure for chroot jail
|
|
log "Phase 8: Setting up chroot jail structure"
|
|
log_cmd "chown root:root $USER_HOME" "Setting ownership for chroot directory"
|
|
log_cmd "chmod 755 $USER_HOME" "Setting permissions for chroot directory"
|
|
|
|
# Create writable data directory for user
|
|
log_cmd "mkdir -p $USER_HOME/data" "Creating data directory"
|
|
log_cmd "chown $USERNAME:$USERNAME $USER_HOME/data" "Setting ownership for data directory"
|
|
log_cmd "chmod 775 $USER_HOME/data" "Setting permissions for data directory"
|
|
log_success "Chroot structure set up"
|
|
|
|
# Create symlink to webroot
|
|
log "Phase 9: Creating symlink to webroot"
|
|
log_cmd "ln -s $ROOT_DIRECTORY $USER_HOME/data/ROOT" "Creating symlink to ROOT directory"
|
|
log_success "Created symlink to $ROOT_DIRECTORY in $USER_HOME/data/ROOT"
|
|
|
|
# Add user to the required groups
|
|
log "Phase 10: Adding user to groups"
|
|
log_cmd "usermod -aG sftpusers $USERNAME" "Adding user to sftpusers group"
|
|
log_success "Added $USERNAME to sftpusers group for chroot access"
|
|
|
|
log_cmd "usermod -aG litespeed $USERNAME" "Adding user to litespeed group"
|
|
log_success "Added $USERNAME to litespeed group for file access"
|
|
|
|
# Create welcome file
|
|
log "Phase 11: Creating welcome file"
|
|
cat > $USER_HOME/data/welcome.txt << EOF
|
|
Welcome to your SFTP account on Jelastic!
|
|
|
|
Your account has been set up with the following details:
|
|
|
|
Username: $USERNAME
|
|
Home Directory: $USER_HOME
|
|
Web Root: $USER_HOME/data/ROOT (symlink to $ROOT_DIRECTORY)
|
|
|
|
For help and support, please contact your system administrator.
|
|
EOF
|
|
log_cmd "chown $USERNAME:$USERNAME $USER_HOME/data/welcome.txt" "Setting welcome file ownership"
|
|
log_cmd "chmod 644 $USER_HOME/data/welcome.txt" "Setting welcome file permissions"
|
|
log_success "Welcome file created"
|
|
|
|
log_success "Script completed successfully for user $USERNAME"
|
|
log "======== SFTP USER SETUP COMPLETE ========"
|
|
|
|
# Export variables for JPS
|
|
log_cmd "echo \"export CREATED_USERNAME=$USERNAME\" >> /etc/profile" "Exporting username variable"
|
|
log_cmd "echo \"export CREATED_PASSWORD=$PASSWORD\" >> /etc/profile" "Exporting password variable" |