#!/bin/bash

# Title: Writable Files Checker
# Description: Check for writable files and directories that could be exploited for privilege escalation
# Author: Jonas Resch

# Check for writable configuration files
check_writable_etc_files() {
  print_subtitle "Writable Files in /etc"
  
  print_info "Checking for writable files in /etc..."
  
  # Find writable files in /etc
  writable_etc=$(find /etc -type f -writable 2>/dev/null)
  
  if [ -n "$writable_etc" ]; then
    print_critical "Found writable files in /etc (potential privilege escalation):"
    echo "$writable_etc" | while read -r file; do
      owner=$(ls -la "$file" 2>/dev/null | awk '{print $3}')
      perms=$(ls -la "$file" 2>/dev/null | awk '{print $1}')
      print_critical " ${RED}${file}${NC} [${perms}] [Owner: ${owner}]"
    done
  else
    print_success "No writable files found in /etc"
  fi
}

# Check for writable path hijacking opportunities
check_path_hijacking() {
  print_subtitle "PATH Hijacking"
  
  print_info "Checking for PATH hijacking opportunities..."
  
  # Get the current PATH
  path_dirs=$(echo "$PATH" | tr ':' '\n')
  
  # Check for writable directories in PATH
  writable_path_dirs=()
  
  for dir in $path_dirs; do
    if [ -d "$dir" ] && [ -w "$dir" ]; then
      writable_path_dirs+=("$dir")
    fi
  done
  
  if [ ${#writable_path_dirs[@]} -gt 0 ]; then
    print_critical "Found writable directories in PATH (potential for PATH hijacking):"
    for dir in "${writable_path_dirs[@]}"; do
      print_critical " ${RED}${dir}${NC}"
    done
    
    print_critical "PATH hijacking can be used to execute arbitrary code when a program is run"
  else
    print_success "No writable directories found in PATH"
  fi
  
  # Check for commonly used commands without absolute paths
  print_info "Checking for commands commonly used without absolute paths..."
  common_cmds=("ls" "cat" "find" "grep" "id" "whoami" "python" "perl" "ruby" "php" "node" "cp" "mv")
  
  for cmd in "${common_cmds[@]}"; do
    cmd_path=$(which "$cmd" 2>/dev/null)
    if [ -n "$cmd_path" ]; then
      # Check if there are any scripts using this command without a full path
      scripts_using_cmd=$(grep -l "^[^#].*[^a-zA-Z0-9\/\._-]$cmd[^a-zA-Z0-9\/\._-]" /etc/cron* /etc/init.d/* /usr/local/bin/* /usr/local/sbin/* 2>/dev/null)
      
      if [ -n "$scripts_using_cmd" ]; then
        print_warning "Command '$cmd' is used without absolute path in scripts:"
        echo "$scripts_using_cmd" | head -n 5 | while read -r script; do
          print_warning " ${YELLOW}${script}${NC}"
        done
        
        if [ -n "${writable_path_dirs[0]}" ]; then
          print_critical "Creating a malicious version in ${writable_path_dirs[0]} may allow privilege escalation"
        fi
      fi
    fi
  done
}

# Check for writable home directory files
check_home_directory_files() {
  print_subtitle "Writable Home Directory Files"
  
  print_info "Checking for writable files in home directories..."
  
  # Check for specific important dot files
  important_dotfiles=(".bashrc" ".bash_profile" ".profile" ".zshrc" ".zshenv" ".zprofile" 
                      ".vimrc" ".ssh/config" ".ssh/authorized_keys" ".config/fish/config.fish"
                      ".cshrc" ".tcshrc" ".kshrc")
  
  current_user=$(whoami)
  
  for dotfile in "${important_dotfiles[@]}"; do
    if [ -f "$HOME/$dotfile" ] && [ -w "$HOME/$dotfile" ]; then
      print_warning "Writable $HOME/$dotfile found (can be used to maintain persistence)"
    fi
  done
  
  # Look for writable files owned by other users or root
  if [ "$THOROUGH" ]; then
    print_info "Looking for writable files owned by others or root (may take a while)..."
    
    other_owned_files=$(find /home -type f -writable ! -user "$current_user" 2>/dev/null | grep -v "/.cache/\|/.config/google-chrome\|/.mozilla/\|/.vscode/\|node_modules/")
    
    if [ -n "$other_owned_files" ]; then
      print_critical "Found writable files owned by other users:"
      echo "$other_owned_files" | while read -r file; do
        owner=$(ls -la "$file" 2>/dev/null | awk '{print $3}')
        print_critical " ${RED}${file}${NC} [Owner: ${owner}]"
      done
      print_critical "These files can be modified to potentially escalate privileges"
    else
      print_success "No writable files owned by other users found"
    fi
  fi
}

# Check for wildcard exploitation opportunities
check_wildcard_injection() {
  print_subtitle "Wildcard Injection"
  
  print_info "Checking for wildcard injection opportunities in scripts..."
  
  # Look for scripts that use wildcards with tar, cp, rsync, etc.
  if [ -d "/etc/cron.daily" ]; then
    wildcard_scripts=$(grep -r -l "\*" /etc/cron.daily /etc/cron.hourly /etc/cron.weekly /etc/cron.monthly /usr/local/bin 2>/dev/null | grep -v ".git")
    
    if [ -n "$wildcard_scripts" ]; then
      print_warning "Found scripts potentially using wildcards:"
      
      echo "$wildcard_scripts" | while read -r script; do
        if grep -q "tar\s.*\*\|cp\s.*\*\|rsync\s.*\*\|chmod\s.*\*\|chown\s.*\*" "$script" 2>/dev/null; then
          print_critical " ${RED}${script}${NC} (contains wildcards with potentially exploitable commands)"
          print_critical "   Run with: ${RED}wildcard_injection_check${NC} $script"
        else
          print_warning " ${YELLOW}${script}${NC} (contains wildcards)"
        fi
      done
      
      print_warning "Wildcard injection could be possible if the script runs with higher privileges"
    else
      print_success "No scripts with wildcard usage found"
    fi
  else
    print_not_found "Cron directories not found or not accessible"
  fi
}

# Main function to run all writable files checks
writable_files_checks() {
  print_title "Writable Files & Directories"
  
  # Run all writable files checks
  check_writable_etc_files
  check_path_hijacking
  check_home_directory_files
  check_wildcard_injection
  
  # Wait for user if wait mode is enabled
  wait_for_user
} 