Перейти к основному содержанию

Drupal — восстановление прав доступа

Drupal 9

Настройка правильных прав доступа к файлам и папкам Drupal — залог хорошего сна администратора сайта. Сегодня пойдёт речь про права доступа в Linux и про настройку доступа из консоли, потребуется доступ по SSH.

Когда нам может понадобиться настройка прав доступа?

  • Когда мы где-то накосячили, поменяли права
  • Когда мы переносим сайт из Windows в Linux
  • Когда мы вручную добавляем какие-то модули
  • Когда кто-то до нас администрировал сайт
  • Когда мы загружаем сайт по FTP или ещё каким-то способом
  • После восстановления сайта
  • И в других случаях, о которых я не подумал

По настройкам прав доступа имеются рекомендации:

https://www.drupal.org/docs/administering-a-drupal-site/security-in-drupal/securing-file-permissions-and-ownership

Владение:

  • drupal_admin:www-data — Core modules/themes files and directories
  • site_admin:www-data — Hosted sites modules/themes/files files and directories

Права:

  • rwxr-x--- — Core modules/themes directories
  • rw-r----- — Core modules/themes files
  • rwxr-x--- — Hosted sites modules/themes directories
  • rw-r----- — Hosted sites modules/themes files
  • rwxrwx--- — Hosted sites "files" directory
  • rw-rw---- — Hosted sites files under "files" directories
  • rwxrwx--- — Hosted sites subdirectories under "files" directories

Чтобы нам вручную не возиться, имеются готовые скрипты:

https://github.com/Metadrop/drupal-fix-permissions-script/

Здесь имеется сам скрипт по настройке прав, и скрипты автоматизации. На всякий случай скопирую себе основной скрипт.

bash

  • #!/bin/bash
    
    # This script sets the right permissions and ownership on a Drupal installation.
    # Loosely based on https://www.drupal.org/node/244924
    #
    # Copyright (C) 2023  Ricardo Sanz Ante
    # This is program is licensed the GPL 3.0. See https://www.gnu.org/licenses/gpl-3.0.html
    # This program comes with ABSOLUTELY NO WARRANTY. This is free software, and you
    # are welcome to redistribute it under certain conditions;
    
    
    # Script usage help.
    function usage() {
    cat <<HELP
    
      SYNOPSIS
    
        `basename "$0"` [OPTION]...
    
    
      DESCRIPTION
    
        This script fixes permissions on a Drupal installation. See
        https://www.drupal.org/node/244924
    
        There are two kinds of files and directories: code and content.
    
        Code are the Drupal codebase, contrib code and configuration files.
        Those should be writable by the deploy user (the user that handles the
        Drupal files) and readable by the webserver. This allows the deploy user to
        modify the code if needed, but prohibits the webserver (the HTTPD process)
        to modify them, increasing security.
    
        Content files and directories are those that hold files used generally as
        content: mainly uploaded files by users and generated files by the server.
        These should be readable and writable by both the deploy user (so they can
        manage them if needed) and the webserver (so the webserver can manage them
        as well).
    
        To allow this, code is owned by the deploy user and belongs to the group
        of the webserver process. The permissions set allows owner to write those
        files and folder but group members can only read them.
        Content files and directories have the same ownership scheme (they are
        owned by the deploy user and belong to the webserver's group) but
        permissions allow both editing and reading.
    
        -u, --drupal_user=<user>: User that manages the Drupal code, the deploy
            user. Mandatory.
    
        -g, --httpd_group=<group>: Web server process group. Files will be assigned
            to this group. Defaults to 'www-data'.
    
        -p, --drupal_path=<path>: Path to the Drupal root directory. Defaults to the
            current directory ('.').
    
        -f, --files-path=<path>: Additional content files directories. Use as much
            times as you need. Relative paths are relative to the Drupal path. This
            is useful when files directory is not under sites directory, for example
            outside the Drupal root.
    
        -s, --setgid: Enable setgid on content files directories. When enabled, all
            files and directories created under a setgid directory will be assigned
            to the group of the setgid directory regardless of the process that
            created the file. This is useful if a user different from the HTTPD user
            creates a file inside a content directory. With setgid, the file will
            be part of the HTTPD group, allowing the HTTPD process to edit or remove
            the file if needed. Otherwise, the HTTPD process lacks the permissions
            to do so.
    
        -n, --dry-run: Perform no action but display information about what would be
            done. Use twice for more information.
    
        -h, --help: Display this help message.
    
    
      EXAMPLES
    
        `basename "$0"` -u=deploy
    
          Fix permissions using 'deploy' as owner, and default values for group
              owner and Drupal Path.
    
        `basename "$0"` -u=deploy -g=www.data
    
          Fix permissions using 'deploy' as owner and 'www-data' as group owner. Use
          the default path to Drupal.
    
        `basename "$0"` -u=deploy -g=www.data -p=/var/vhosts/drupal/web
    
          Fix permissions using 'deploy' as owner and 'www-data' as group owner.
          Finds the Drupal in '/var/vhosts/drupal/web'.
    
        `basename "$0"` -u=deploy -s
    
          Fix permissions using 'deploy' as owner, and defaults value for group
          owner and Drupal Path. Sets the setgid bit to the content files
          directories.
    
        `basename "$0"` -u=deploy -f=../private
    
          Fix permissions using 'deploy' as owner, and defaults value for group
          owner and Drupal Path. Process an additional content directory at
          '../private', relative to the Drupal path.
    
        `basename "$0"` -u=deploy -n -n
    
          Display the list of files and directories that would be fixed, using
          'deploy' as owner, and default values for group owner and Drupal Path.
    
    
    HELP
    }
    
    
    # Determines if current user is the root user.
    #
    # Returns:
    #  0 if it is the root user.
    #  1 if it is not the root user.
    function is_root_user() {
      [ $(id -u) == 0 ]
    }
    
    
    # Determines if a user exists in the system.
    #
    # Returns:
    #  0 if it is the root user.
    #  1 if it is not the root user.
    function is_valid_user() {
      [ ! -z "$1" ] && [[ $(id -un "$1" 2> /dev/null) == "$1" ]]
    }
    
    
    # Determines if a path is a Drupal root directory.
    #
    # The function checks that the path exists, it has a "sites" directory and tries
    # to find the ssytem.module file. It detects Drupal 7/8/9/10.
    #
    # Params:
    #  $1 Path to check.
    #
    # Returns:
    #  0 if it is a Drupal root directory.
    #  1 if it is not a Drupal root directory.
    is_drupal_root() {
      [ ! -z "$1" ]  && [ -d "$1"  ] && [ -d "$1/sites" ] && ([ -f "$1/core/modules/system/system.module" ] || [ -f "$1/modules/system/system.module" ])
    }
    
    
    # Sets the right owners for a given directory.
    #
    # Find any file or folder that is not owned by the drupal user or its group is
    # not the web server group and fixes the ownership.
    #
    # Params:
    #  $1 Path to the directory to process.
    #
    # Globals:
    #  drupal_user: user to own the files and directories.
    #  httpd_group: group to own the files and directories.
    function fix_onwership() {
      case $simulate in
        0)
        # Real action.
        find "$1" $detected_vendor_path \( ! -user $drupal_user -o ! -group $httpd_group \) \( -type f -o -type d \) -print0 | xargs -r -0 -L20 chown  $drupal_user:$httpd_group
        ;;
    
        1)
        # Simulate.
        printf "\n    Items with wrong ownership: "
        find "$1" $detected_vendor_path \( ! -user $drupal_user -o ! -group $httpd_group \) \( -type f -o -type d \) -print | wc -l
        ;;
    
        2)
        # Simulate verbosely.
        printf "\n    Files and directories that would have their ownership fixed: "
        # Use a variable to indent output.
        items=$(find "$1" $detected_vendor_path \( ! -user $drupal_user -o ! -group $httpd_group \) \( -type f -o -type d \) -print)
        items=${items:-None}
        printf "\n      ${items//$'\n'/$'\n'      }\n"
        ;;
      esac
    }
    
    
    # Helper function to set the permissions on code files and folders.
    #
    # This is an internal function.
    #
    # Params:
    #  $1 Path to the directory to process.
    #  $2 Type of element to process. f for files, d for directories.
    #  $3 Permissions wanted compatible with chmod . Exmaple: u=rwx,g=rwxs,o=
    function fix_code_permission_helper() {
      case $simulate in
        0)
        # Real action.
        find "$1" \( -path "$1"/sites/\*/$file_folder_name -prune \) -o \( -path "$1"/sites/\*/$private_folder_name -prune \) -o \( -type $2 ! -perm $3 -print0 \) | xargs -r -0 -L4 chmod $3
        ;;
    
        1)
        # Simulate.
        num=$(find "$1" \( -path "$1"/sites/\*/$file_folder_name -prune \) -o \( -path "$1"/sites/\*/$private_folder_name -prune \) -o \( -type $2 ! -perm $3 -print \) | wc -l)
        printf "\n    Code items with wrong permissions: $num"
        ;;
    
        2)
        # Simulate verbosely.
        printf "\n    Code files and directories that would have their permissions fixed: "
        # Use a variable to indent output.
        items=$(find "$1" \( -path "$1"/sites/\*/$file_folder_name -prune \) -o \( -path "$1"/sites/\*/$private_folder_name -prune \) -o \( -type $2 ! -perm $3 -print \))
        items=${items:-None}
        printf "\n      ${items//$'\n'/$'\n'      }\n"
        ;;
      esac
    }
    
    
    # Helper function to set the permissions on content files and folders.
    #
    # This is an internal function.
    #
    # Params:
    #  $1 Path to the directory to process.
    #  $2 Type of element to process. f for files, d for directories.
    #  $3 Permissions wanted compatible with chmod . Exmaple: u=rwx,g=rwxs,o=
    function fix_content_permission_helper() {
      case $simulate in
        0)
        # Real action.
        find "$1" -type $2 ! -perm $3 -print0 | xargs -r -0 -L20 chmod $3
        ;;
    
        1)
        # Simulate.
        num=$(find "$1" -type $2 ! -perm $3 -print | wc -l)
        printf "\n      Content items with wrong permissions: $num"
        ;;
    
        2)
        # Simulate verbosely.
        printf "\n      Content files and directories that would have their permissions fixed: "
        # Use a variable to indent output.
        items=$(find "$1" -type $2 ! -perm $3 -print)
        items=${items:-None}
        printf "\n        ${items//$'\n'/$'\n'        }\n"
        ;;
    
      esac
    }
    
    
    # Sets the permissions of a code path.
    #
    # Params:
    #  $1 Path to process.
    #
    # Globals:
    #  code_dir_perms: permissions scheme to use for code directories.
    #  code_file_perms permissions scheme to use for code files.
    function fix_code_permissions() {
    
      name=$(basename "$1")
      printf "\n  Setting permissions on code directories to $code_dir_perms under '$name'"
      fix_code_permission_helper "$1" d "$code_dir_perms"
    
      printf "\n  Setting permissions on code files to $code_file_perms under '$name'"
      fix_code_permission_helper "$1" f "$code_file_perms"
    
    
      if [ ! -z "$detected_vendor_path" ]
      then
        printf "\n  Setting permissions on vendor code directories to $code_dir_perms under '$detected_vendor_path'"
        fix_code_permission_helper "$detected_vendor_path" d "$code_dir_perms"
    
        printf "\n  Removing all permissions on vendor code files to other users ($vendor_code_file_perms) under '$detected_vendor_path'"
        fix_code_permission_helper "$detected_vendor_path" f "$vendor_code_file_perms"
      fi
    
    }
    
    
    # Sets the permissions of a content path.
    #
    # Params:
    #  $1 Path to process.
    #
    # Globals:
    #  content_dir_perms: permissions scheme to use for content directories.
    #  content_file_perms permissions scheme to use for content files.
    function fix_content_permissions() {
    
      name=$(basename "$1")
      printf "\n    Setting permissions on content directories to $content_dir_perms under '$name'"
      fix_content_permission_helper "$1" d "$content_dir_perms"
    
      printf "\n    Setting permissions on content files to $content_file_perms under '$name'"
      fix_content_permission_helper "$1" f "$content_file_perms"
    }
    
    
    
    # Main code
    ###########
    #
    
    
    printf "Script to fix permissions in a Drupal installation"
    
    # Default values.
    DEFAULT_DRUPAL_PATH=.
    DEFAULT_HTTPD_GROPUP="www-data"
    
    # Initialize some values.
    group_executable_mode=x
    additional_files_paths=""
    file_folder_name='files'
    private_folder_name='private'
    simulate=0
    
    
    # Parse Command Line Arguments
    while [ "$#" -gt 0 ]; do
      case "$1" in
        --drupal_path=* | -p=*)
          drupal_path="${1#*=}"
          ;;
        --drupal_user=* | -u=*)
          drupal_user="${1#*=}"
          ;;
        --httpd_group=* | -g=*)
          httpd_group="${1#*=}"
          ;;
        --files-path=* | -f=*)
          # Add a new line if there is any previous element.
          if [ ! -z "$additional_files_paths" ]
          then
            additional_files_paths+='\n'
          fi
          # Add path to the path list.
          additional_files_paths=$(printf "${additional_files_paths}${1#*=}")
          ;;
        --setgid | -s)
          group_executable_mode=xs
          ;;
        --dry-run | -n)
          simulate=$((simulate  + 1))
          ;;
        --help | -h)
          usage
          exit 0
          ;;
        *)
          printf "\nError: Invalid parameter '$1'\n"
          exit 1
      esac
      shift
    done
    
    
    # Initialize undefined values with default values.
    if [ -z $drupal_path ]
    then
      drupal_path=$DEFAULT_DRUPAL_PATH
      printf "\nUsing default Drupal path '$DEFAULT_DRUPAL_PATH'"
    fi
    
    if [ -z $httpd_group ]
    then
      httpd_group=$DEFAULT_HTTPD_GROPUP
      printf "\nUsing default HTTPD group '$DEFAULT_HTTPD_GROPUP'"
    fi
    
    
    
    # Calculate permissions by object type (directory or file) and function (code or
    # content files).
    code_dir_perms='u=rwx,g=rx,o='
    code_file_perms='u=rw,g=r,o='
    vendor_code_file_perms='o='
    content_dir_perms="u=rwx,g=rw${group_executable_mode},o="
    content_file_perms='ug=rw,o='
    
    
    
    # Go to the right place (this a kind of initialization).
    cd $drupal_path
    complete_drupal_path=$(pwd)
    
    # Check if there's a vendor folder in the upper folder.
    [ -d "../vendor" ] && [ -f "../composer.json" ] && detected_vendor_path="../vendor"
    
    
    # Show current configuration.
    #############################
    printf "\nRunning configuration:
    Path: $complete_drupal_path
    Owner user: $drupal_user
    Owner group: $httpd_group
    Code dirs perms: $code_dir_perms
    Code files perms: $code_file_perms
    Separated vendor folder detected: ${detected_vendor_path:-"No"}
    Content dirs perms: $content_dir_perms
    Content files perms: $content_file_perms
    File folder name: $file_folder_name
    Private files folder name: $private_folder_name
    "
    if [ ! -z "${additional_files_paths}" ]
    then
      printf "Additional content directories to process:\n${additional_files_paths}"
    fi
    
    
    # Sanity checks.
    ################
    #
    
    is_root_user
    if [ $? -ne 0 ]
    then
      printf "\nError: you must run this script as the root user\n"
      exit 1
    fi
    
    is_drupal_root $drupal_path
    if [ $? -ne 0 ]
    then
      printf "\nError: provided path '$drupal_path' is not the root directory of a Drupal installation\n"
      exit 1
    fi
    
    
    if [ -z $drupal_user ]
    then
      printf "\nError: no user provided\n"
      exit 1
    fi
    
    
    is_valid_user $drupal_user
    if [ $? -ne 0 ]
    then
      printf "\nError: provided user '$drupal_user' is not a valid user\n"
      exit 1
    fi
    
    
    
    # Do the job
    ############
    #
    
    printf "\n\nAll checks passed, go!"
    printf "\nProcessing Drupal installed on '$complete_drupal_path'"
    
    # First, fix ownership.
    printf "\nFixing ownership of files and directories"
    fix_onwership "$complete_drupal_path"
    echo "$additional_files_paths"| while read path; do
      [ -d "$path" ] && fix_onwership "$path"
    done
    
    # Second, fix permissions on code.
    printf "\nFixing permissions on code files and directories"
    fix_code_permissions "$complete_drupal_path"
    
    # Third, fix permissions on content.
    printf "\nFixing permissions on content files and directories under 'sites' folder"
    find "$complete_drupal_path/sites/" -maxdepth 1 -mindepth 1 -type d| while read site_folder
    do
      printf "\n  Checking folder "
      printf $(basename "$site_folder")
      [ -d "$site_folder/$file_folder_name" ] && fix_content_permissions "$site_folder/$file_folder_name"
      [ -d "$site_folder/$private_folder_name" ] && fix_content_permissions "$site_folder/$private_folder_name"
    done
    
    [ -z "$additional_files_paths" ] && printf "\nProcessing additional content folders"
    echo "$additional_files_paths"| while read path; do
      [ -d "$path" ] && fix_content_permissions "$path"
    done
    
    printf "\n\nPermissions and ownership fixed!\n"

sh

  • #!/bin/sh
    
    # This script sets the right permissions and ownership on a Drupal installation.
    # Loosely based on https://www.drupal.org/node/244924
    # Adapted for POSIX sh (not bash-only)
    
    # Script usage help.
    usage() {
    cat <<HELP
    
      SYNOPSIS
    
        `basename "$0"` [OPTION]...
    
    
      DESCRIPTION
    
        This script fixes permissions on a Drupal installation. See
        https://www.drupal.org/node/244924
    
        -u, --drupal_user=<user>: User that manages the Drupal code, the deploy
            user. Mandatory.
    
        -g, --httpd_group=<group>: Web server process group. Defaults to 'www-data'.
    
        -p, --drupal_path=<path>: Path to the Drupal root directory. Defaults to '.'.
    
        -f, --files-path=<path>: Additional content files directories.
    
        -s, --setgid: Enable setgid on content files directories.
    
        -n, --dry-run: Perform no action. Use twice for more information.
    
        -h, --help: Display this help message.
    
    HELP
    }
    
    # Determines if current user is the root user.
    is_root_user() {
      [ $(id -u) -eq 0 ]
    }
    
    # Determines if a user exists in the system.
    is_valid_user() {
      [ -n "$1" ] && [ "$(id -un "$1" 2> /dev/null)" = "$1" ]
    }
    
    # Determines if a path is a Drupal root directory.
    is_drupal_root() {
      [ -n "$1" ] && [ -d "$1" ] && [ -d "$1/sites" ] && \
      ( [ -f "$1/core/modules/system/system.module" ] || [ -f "$1/modules/system/system.module" ] )
    }
    
    # Sets the right owners for a given directory.
    fix_ownership() {
      case $simulate in
        0)
        find "$1" $detected_vendor_path \( ! -user $drupal_user -o ! -group $httpd_group \) \( -type f -o -type d \) -exec chown $drupal_user:$httpd_group {} +
        ;;
        1)
        printf "\n    Items with wrong ownership: "
        find "$1" $detected_vendor_path \( ! -user $drupal_user -o ! -group $httpd_group \) \( -type f -o -type d \) -print | wc -l
        ;;
        2)
        printf "\n    Files and directories that would have their ownership fixed: "
        items=$(find "$1" $detected_vendor_path \( ! -user $drupal_user -o ! -group $httpd_group \) \( -type f -o -type d \) -print 2>/dev/null)
        if [ -z "$items" ]; then
          printf "\n      None\n"
        else
          echo "$items" | sed 's/^/      /'
        fi
        ;;
      esac
    }
    
    # Helper function to set the permissions on code files and folders.
    fix_code_permission_helper() {
      case $simulate in
        0)
        find "$1" \( -path "$1"/sites/*/$file_folder_name -prune \) -o \
               \( -path "$1"/sites/*/$private_folder_name -prune \) -o \
               \( -type $2 ! -perm $3 -exec chmod $3 {} + \)
        ;;
        1)
        num=$(find "$1" \( -path "$1"/sites/*/$file_folder_name -prune \) -o \
                   \( -path "$1"/sites/*/$private_folder_name -prune \) -o \
                   \( -type $2 ! -perm $3 -print \) | wc -l)
        printf "\n    Code items with wrong permissions: $num"
        ;;
        2)
        printf "\n    Code files and directories that would have their permissions fixed: "
        items=$(find "$1" \( -path "$1"/sites/*/$file_folder_name -prune \) -o \
                     \( -path "$1"/sites/*/$private_folder_name -prune \) -o \
                     \( -type $2 ! -perm $3 -print \) 2>/dev/null)
        if [ -z "$items" ]; then
          printf "\n      None\n"
        else
          echo "$items" | sed 's/^/      /'
        fi
        ;;
      esac
    }
    
    # Helper function to set the permissions on content files and folders.
    fix_content_permission_helper() {
      case $simulate in
        0)
        find "$1" -type $2 ! -perm $3 -exec chmod $3 {} +
        ;;
        1)
        num=$(find "$1" -type $2 ! -perm $3 -print | wc -l)
        printf "\n      Content items with wrong permissions: $num"
        ;;
        2)
        printf "\n      Content files and directories that would have their permissions fixed: "
        items=$(find "$1" -type $2 ! -perm $3 -print 2>/dev/null)
        if [ -z "$items" ]; then
          printf "\n        None\n"
        else
          echo "$items" | sed 's/^/        /'
        fi
        ;;
      esac
    }
    
    # Sets the permissions of a code path.
    fix_code_permissions() {
      name=$(basename "$1")
      printf "\n  Setting permissions on code directories to $code_dir_perms under '$name'"
      fix_code_permission_helper "$1" d "$code_dir_perms"
    
      printf "\n  Setting permissions on code files to $code_file_perms under '$name'"
      fix_code_permission_helper "$1" f "$code_file_perms"
    
      if [ -n "$detected_vendor_path" ]; then
        printf "\n  Setting permissions on vendor code directories to $code_dir_perms under '$detected_vendor_path'"
        fix_code_permission_helper "$detected_vendor_path" d "$code_dir_perms"
    
        printf "\n  Removing all permissions on vendor code files to other users ($vendor_code_file_perms) under '$detected_vendor_path'"
        fix_code_permission_helper "$detected_vendor_path" f "$vendor_code_file_perms"
      fi
    }
    
    # Sets the permissions of a content path.
    fix_content_permissions() {
      name=$(basename "$1")
      printf "\n    Setting permissions on content directories to $content_dir_perms under '$name'"
      fix_content_permission_helper "$1" d "$content_dir_perms"
    
      printf "\n    Setting permissions on content files to $content_file_perms under '$name'"
      fix_content_permission_helper "$1" f "$content_file_perms"
    }
    
    # Main code
    ###########
    
    printf "Script to fix permissions in a Drupal installation"
    
    # Default values.
    DEFAULT_DRUPAL_PATH=.
    DEFAULT_HTTPD_GROUP="www-data"
    
    # Initialize some values.
    group_executable_mode=x
    additional_files_paths=""
    file_folder_name='files'
    private_folder_name='private'
    simulate=0
    
    # Parse Command Line Arguments
    while [ "$#" -gt 0 ]; do
      case "$1" in
        --drupal_path=* | -p=*)
          drupal_path="${1#*=}"
          ;;
        --drupal_user=* | -u=*)
          drupal_user="${1#*=}"
          ;;
        --httpd_group=* | -g=*)
          httpd_group="${1#*=}"
          ;;
        --files-path=* | -f=*)
          if [ -n "$additional_files_paths" ]; then
            additional_files_paths="${additional_files_paths}\n${1#*=}"
          else
            additional_files_paths="${1#*=}"
          fi
          ;;
        --setgid | -s)
          group_executable_mode=xs
          ;;
        --dry-run | -n)
          simulate=$((simulate + 1))
          ;;
        --help | -h)
          usage
          exit 0
          ;;
        *)
          printf "\nError: Invalid parameter '$1'\n"
          exit 1
      esac
      shift
    done
    
    # Initialize undefined values with default values.
    if [ -z "$drupal_path" ]; then
      drupal_path=$DEFAULT_DRUPAL_PATH
      printf "\nUsing default Drupal path '$DEFAULT_DRUPAL_PATH'"
    fi
    
    if [ -z "$httpd_group" ]; then
      httpd_group=$DEFAULT_HTTPD_GROUP
      printf "\nUsing default HTTPD group '$DEFAULT_HTTPD_GROUP'"
    fi
    
    # Calculate permissions
    code_dir_perms='u=rwx,g=rx,o='
    code_file_perms='u=rw,g=r,o='
    vendor_code_file_perms='o='
    content_dir_perms="u=rwx,g=rw${group_executable_mode},o="
    content_file_perms='ug=rw,o='
    
    # Go to the right place
    cd "$drupal_path" 2>/dev/null || exit 1
    complete_drupal_path=$(pwd)
    
    # Check for vendor folder
    detected_vendor_path=""
    [ -d "../vendor" ] && [ -f "../composer.json" ] && detected_vendor_path="../vendor"
    
    # Show current configuration
    printf "\nRunning configuration:
    Path: $complete_drupal_path
    Owner user: $drupal_user
    Owner group: $httpd_group
    Code dirs perms: $code_dir_perms
    Code files perms: $code_file_perms
    Separated vendor folder detected: ${detected_vendor_path:-"No"}
    Content dirs perms: $content_dir_perms
    Content files perms: $content_file_perms
    File folder name: $file_folder_name
    Private files folder name: $private_folder_name
    "
    
    if [ -n "$additional_files_paths" ]; then
      printf "Additional content directories to process:\n${additional_files_paths}\n"
    fi
    
    # Sanity checks
    if ! is_root_user; then
      printf "\nError: you must run this script as the root user\n"
      exit 1
    fi
    
    if ! is_drupal_root "$drupal_path"; then
      printf "\nError: provided path '$drupal_path' is not the root directory of a Drupal installation\n"
      exit 1
    fi
    
    if [ -z "$drupal_user" ]; then
      printf "\nError: no user provided\n"
      exit 1
    fi
    
    if ! is_valid_user "$drupal_user"; then
      printf "\nError: provided user '$drupal_user' is not a valid user\n"
      exit 1
    fi
    
    # Do the job
    printf "\n\nAll checks passed, go!"
    printf "\nProcessing Drupal installed on '$complete_drupal_path'"
    
    # Fix ownership
    printf "\nFixing ownership of files and directories"
    fix_ownership "$complete_drupal_path"
    
    # Process additional paths
    echo "$additional_files_paths" | while read -r path; do
      [ -n "$path" ] && [ -d "$path" ] && fix_ownership "$path"
    done
    
    # Fix permissions on code
    printf "\nFixing permissions on code files and directories"
    fix_code_permissions "$complete_drupal_path"
    
    # Fix permissions on content under sites
    printf "\nFixing permissions on content files and directories under 'sites' folder"
    for site_folder in $(find "$complete_drupal_path/sites/" -maxdepth 1 -mindepth 1 -type d 2>/dev/null); do
      printf "\n  Checking folder $(basename "$site_folder")"
      [ -d "$site_folder/$file_folder_name" ] && fix_content_permissions "$site_folder/$file_folder_name"
      [ -d "$site_folder/$private_folder_name" ] && fix_content_permissions "$site_folder/$private_folder_name"
    done
    
    # Process additional content folders
    if [ -n "$additional_files_paths" ]; then
      printf "\nProcessing additional content folders"
      echo "$additional_files_paths" | while read -r path; do
        [ -n "$path" ] && [ -d "$path" ] && fix_content_permissions "$path"
      done
    fi
    
    printf "\n\nPermissions and ownership fixed!\n"

Помощь:

drupal_fix_permissions.sh -h

Пример:

drupal_fix_permissions.sh -u=www-data -g=www-data -p=/var/www/html/drupal/

drupal

Если нет прав root?

Если у вас нет прав root и вы пользуетесь хостингом, то может помочь скрипт, который не меняет владельца, а только управляет правами доступа.

sh

  • #!/bin/sh
    
    # Full Drupal 10 permissions script for MULTISITE (no root needed)
    # Works with FTP/SSH access without sudo
    
    usage() {
    cat <<HELP
      SYNOPSIS
        `basename "$0"` [OPTION]...
    
      DESCRIPTION
        Sets correct permissions for Drupal 10 MULTISITE without changing ownership.
        
        -p, --drupal_path=<path>: Path to Drupal root (default: current directory)
        -s, --setgid: Enable setgid (2775 instead of 775) on content directories
        -n, --dry-run: Show what would be done (use twice for details)
        -h, --help: Show this help
    
      MULTISITE NOTES
        Script processes ALL sites under sites/*/
        Each site's settings.php is set to 440 (owner+group read)
        Each site's files/ and private/ directories are handled separately
    
    HELP
    }
    
    # Default values
    DRUPAL_PATH="."
    group_executable_mode="x"
    simulate=0
    
    # Parse arguments
    while [ "$#" -gt 0 ]; do
      case "$1" in
        -p=*|--drupal_path=*)
          DRUPAL_PATH="${1#*=}"
          ;;
        -s|--setgid)
          group_executable_mode="xs"
          ;;
        -n|--dry-run)
          simulate=$((simulate + 1))
          ;;
        -h|--help)
          usage
          exit 0
          ;;
        *)
          printf "Error: Invalid parameter '$1'\n"
          exit 1
      esac
      shift
    done
    
    # Go to Drupal root
    cd "$DRUPAL_PATH" 2>/dev/null || { printf "Error: Path '$DRUPAL_PATH' not found\n"; exit 1; }
    DRUPAL_PATH=$(pwd)
    
    printf "\n=== Drupal 10 MULTISITE Permissions Fix ===\n"
    printf "Path: $DRUPAL_PATH\n"
    printf "Setgid: $([ "$group_executable_mode" = "xs" ] && echo "YES (2775)" || echo "NO (775)")\n"
    printf "Dry-run level: $simulate\n"
    printf "Mode: MULTISITE (processing all sites under sites/)\n\n"
    
    # Verify Drupal root
    if [ ! -d "sites" ] || { [ ! -f "core/modules/system/system.module" ] && [ ! -f "modules/system/system.module" ]; }; then
      printf "Error: '$DRUPAL_PATH' does not appear to be a Drupal 10 root\n"
      exit 1
    fi
    
    # Permission definitions
    CODE_DIRS="755"        # rwx r-x r-x
    CODE_FILES="644"       # rw- r-- r--
    VENDOR_DIRS="555"      # r-x r-x r-x (no write for anyone)
    VENDOR_FILES="444"     # r-- r-- r-- (read-only)
    CONTENT_DIRS="775"     # rwx rwx r-x
    CONTENT_FILES="664"    # rw- rw- r--
    SETTINGS_PERMS="440"   # r-- r-- --- (owner+group read, no write, others no access)
    HTACCESS="444"         # read-only for .htaccess
    
    if [ "$group_executable_mode" = "xs" ]; then
      CONTENT_DIRS="2775"  # setgid version
    fi
    
    # Helper function to execute or simulate
    run_cmd() {
      if [ $simulate -eq 0 ]; then
        eval "$1" 2>/dev/null
        return $?
      else
        if [ $simulate -ge 2 ]; then
          echo "  [DRY RUN] $1"
        fi
        return 0
      fi
    }
    
    # Count sites
    SITE_COUNT=$(find "$DRUPAL_PATH/sites" -maxdepth 1 -mindepth 1 -type d ! -name "*.php" ! -name "*.txt" 2>/dev/null | wc -l)
    printf "Found $SITE_COUNT site(s) to process\n"
    
    # 1. Fix all standard directories (excluding content directories and vendor)
    printf "\n1. Setting code directories to $CODE_DIRS (all sites)\n"
    find_cmd="find \"$DRUPAL_PATH\" -type d \
      ! -path \"*/sites/*/files*\" \
      ! -path \"*/sites/*/private*\" \
      ! -path \"*/vendor*\" \
      -exec chmod $CODE_DIRS {} +"
    run_cmd "$find_cmd"
    
    # 2. Fix all standard files (excluding content files and vendor)
    printf "\n2. Setting code files to $CODE_FILES (all sites)\n"
    find_cmd="find \"$DRUPAL_PATH\" -type f \
      ! -path \"*/sites/*/files*\" \
      ! -path \"*/sites/*/private*\" \
      ! -path \"*/vendor*\" \
      -exec chmod $CODE_FILES {} +"
    run_cmd "$find_cmd"
    
    # 3. Handle vendor directory if exists
    if [ -d "$DRUPAL_PATH/vendor" ]; then
      printf "\n3. Securing vendor directory to $VENDOR_DIRS/$VENDOR_FILES\n"
      find_cmd="find \"$DRUPAL_PATH/vendor\" -type d -exec chmod $VENDOR_DIRS {} +"
      run_cmd "$find_cmd"
      find_cmd="find \"$DRUPAL_PATH/vendor\" -type f -exec chmod $VENDOR_FILES {} +"
      run_cmd "$find_cmd"
    fi
    
    # 4. Process EACH site in multisite
    printf "\n4. Processing each site's settings.php and directories\n"
    
    for site_dir in "$DRUPAL_PATH/sites/"*/; do
      # Normalize path (remove trailing slash)
      site_name=$(basename "$site_dir")
      site_path="${site_dir%/}"
      
      printf "\n  --- Site: $site_name ---\n"
      
      # 4a. Set site directory permissions to 755
      printf "    Setting site directory to 755\n"
      run_cmd "chmod 755 \"$site_path\""
      
      # 4b. Protect settings.php for this site (if exists)
      if [ -f "$site_path/settings.php" ]; then
        printf "    Setting $site_path/settings.php to $SETTINGS_PERMS\n"
        run_cmd "chmod $SETTINGS_PERMS \"$site_path/settings.php\""
      else
        printf "    No settings.php found in $site_path (using default?)\n"
        # Check for default.settings.php
        if [ -f "$site_path/default.settings.php" ]; then
          printf "    default.settings.php present (template file, keeping as is)\n"
        fi
      fi
      
      # 4c. Protect .htaccess in site root (if exists)
      if [ -f "$site_path/.htaccess" ]; then
        printf "    Setting $site_path/.htaccess to $HTACCESS\n"
        run_cmd "chmod $HTACCESS \"$site_path/.htaccess\""
      fi
      
      # 4d. Handle files directory for this site
      if [ -d "$site_path/files" ]; then
        printf "    Setting content directories in $site_path/files to $CONTENT_DIRS\n"
        run_cmd "find \"$site_path/files\" -type d -exec chmod $CONTENT_DIRS {} +"
        
        printf "    Setting content files in $site_path/files to $CONTENT_FILES\n"
        run_cmd "find \"$site_path/files\" -type f -exec chmod $CONTENT_FILES {} +"
        
        # Protect .htaccess inside files
        if [ -f "$site_path/files/.htaccess" ]; then
          printf "    Protecting $site_path/files/.htaccess to $HTACCESS\n"
          run_cmd "chmod $HTACCESS \"$site_path/files/.htaccess\""
        fi
      else
        printf "    No files directory found in $site_path\n"
      fi
      
      # 4e. Handle private directory for this site (if exists)
      if [ -d "$site_path/private" ]; then
        printf "    Setting content directories in $site_path/private to $CONTENT_DIRS\n"
        run_cmd "find \"$site_path/private\" -type d -exec chmod $CONTENT_DIRS {} +"
        
        printf "    Setting content files in $site_path/private to $CONTENT_FILES\n"
        run_cmd "find \"$site_path/private\" -type f -exec chmod $CONTENT_FILES {} +"
        
        # Protect .htaccess inside private
        if [ -f "$site_path/private/.htaccess" ]; then
          printf "    Protecting $site_path/private/.htaccess to $HTACCESS\n"
          run_cmd "chmod $HTACCESS \"$site_path/private/.htaccess\""
        fi
      fi
    done
    
    # 5. Handle sites.php if exists (multisite mapping file)
    if [ -f "$DRUPAL_PATH/sites/sites.php" ]; then
      printf "\n5. Protecting sites.php (multisite mapping)\n"
      run_cmd "chmod 644 \"$DRUPAL_PATH/sites/sites.php\""
    fi
    
    # Summary
    if [ $simulate -gt 0 ]; then
      printf "\n=== DRY RUN COMPLETE ===\n"
      printf "Run without -n to apply changes.\n"
      if [ $simulate -eq 1 ]; then
        printf "Use -n -n for verbose dry-run output.\n"
      fi
    else
      printf "\n=== PERMISSIONS APPLIED ===\n"
      printf "All $SITE_COUNT site(s) processed.\n"
    fi
    
    printf "\nVerification commands:\n"
    printf "  ls -la sites/*/settings.php\n"
    printf "  ls -la sites/*/files/\n"
    printf "  drush @sites cr (clear cache for all sites if using drush)\n\n"

Теги

 

Похожие материалы

Критическая уязвимость Drupal Core — CVE-2022-25277

Для ядра Drupal выпустили исправления критической уязвимости CVE-2022-25277. Уязвимость получила 15 баллов из 25 возможных по шкале, принятой на Drupal. Возможно удалённое выполнение кода PHP.

Теги

CTF — HTTP Headers

Продолжаем решать задачки по информационной безопасности web-серверов. Сегодня задачка с портала root-me.org, называется "HTTP - Headers". За решение задачки дают 15 баллов, чуть посложнее начального уровня.

Теги