Add support for static sites with chrooted SFTP access in create_vhost.sh and new permission repair script

This commit is contained in:
chris committed 2026-11-16 14:41:47 +01:00
1 parent 6f231e4a0a
commit 76f0fe1a7a
3 files changed
+759 -13

No files matched your search

+19
View File
@@ -72,3 +72,22 @@
# - Defaults to 'false' # - Defaults to 'false'
# - # -
#CREATE_SYMLINK_WEB_BASE_DIR= #CREATE_SYMLINK_WEB_BASE_DIR=
# - Group for chrooted SFTP users (vhost type "static site with suEXEC
# - (chrooted SFTP access)").
# -
# - sshd must restrict members of this group, i.e. at the end of
# - /etc/ssh/sshd_config:
# -
# - Match Group sftp-chroot
# - ChrootDirectory %h
# - ForceCommand internal-sftp -u 0027
# - AllowTcpForwarding no
# - AllowAgentForwarding no
# - X11Forwarding no
# - PermitTunnel no
# - PermitTTY no
# -
# - Defaults to 'sftp-chroot'
# -
#SFTP_CHROOT_GROUP=""
+234 -13
View File
@@ -48,7 +48,9 @@ cat<<EOF
created. created.
-t <type> -t <type>
One of "PHP-FPM", "FCGID", "MOD_PHP" or "STATIC". One of "PHP-FPM", "FCGID", "MOD_PHP", "STATIC" or "STATIC-SFTP".
"STATIC-SFTP" creates a static site with suEXEC user, who can
access the website's base directory via chrooted SFTP.
If not give, the site url will be requested. If not give, the site url will be requested.
-s -s
@@ -285,6 +287,9 @@ _tcp_port=9000
__CUSTOM_IP_LOG=ip_requests.log __CUSTOM_IP_LOG=ip_requests.log
_suEXEC=false _suEXEC=false
set_suEXEC_password=false
_sftp_chroot=false
_sshd_chroot_missing=false
_auto="" _auto=""
site_url="" site_url=""
_type="" _type=""
@@ -304,6 +309,11 @@ VHOST_DIR=""
WEBSITES_ROOT_DIR="" WEBSITES_ROOT_DIR=""
CREATE_SYMLINK_WEB_BASE_DIR=false CREATE_SYMLINK_WEB_BASE_DIR=false
# - Static site with suEXEC and chrooted SFTP access:
# - sshd has to restrict members of that group to (chrooted) sftp
# -
SFTP_CHROOT_GROUP="sftp-chroot"
# --- # ---
# - Determin timeout value # - Determin timeout value
@@ -385,8 +395,12 @@ while getopts aChl:n:p:sS:t:u:V:v: opt ; do
_connection_msg="Unix Socket" _connection_msg="Unix Socket"
fi fi
;; ;;
t) if [ "$OPTARG" = "PHP-FPM" -o "$OPTARG" = "FCGID" -o "$OPTARG" = "MOD_PHP" ]; then t) if [ "$OPTARG" = "PHP-FPM" -o "$OPTARG" = "FCGID" -o "$OPTARG" = "MOD_PHP" -o "$OPTARG" = "STATIC" ]; then
_type=$OPTARG _type=$OPTARG
elif [ "$OPTARG" = "STATIC-SFTP" ]; then
_type="STATIC"
_suEXEC=true
_sftp_chroot=true
fi fi
;; ;;
u) site_url=$OPTARG ;; u) site_url=$OPTARG ;;
@@ -477,6 +491,7 @@ if [ "$_type" != "PHP-FPM" -a "$_type" != "FCGID" -a "$_type" != "MOD_PHP" -a "$
echo "[5] static site (No PHP engine enabled)" echo "[5] static site (No PHP engine enabled)"
echo "[6] only redirect" echo "[6] only redirect"
echo "[7] parke domain/site" echo "[7] parke domain/site"
echo "[8] static site with suEXEC (chrooted SFTP access, No PHP engine enabled)"
echo "" echo ""
echononl "Your choice: " echononl "Your choice: "
while [ "$_type" != "PHP-FPM" -a "$_type" != "FCGID" -a "$_type" != "MOD_PHP" -a "$_type" != "STATIC" -a "$_type" != "REDIRECT" -a "$_type" != "PARKED" ];do while [ "$_type" != "PHP-FPM" -a "$_type" != "FCGID" -a "$_type" != "MOD_PHP" -a "$_type" != "STATIC" -a "$_type" != "REDIRECT" -a "$_type" != "PARKED" ];do
@@ -511,8 +526,14 @@ if [ "$_type" != "PHP-FPM" -a "$_type" != "FCGID" -a "$_type" != "MOD_PHP" -a "$
_type_msg="parke domai/site" _type_msg="parke domai/site"
_new_extension=parked _new_extension=parked
;; ;;
8) _type="STATIC"
_suEXEC=true
_sftp_chroot=true
_type_msg="static site with suEXEC (chrooted SFTP access)"
_new_extension=static-suexec
;;
*) echo "" *) echo ""
echo -e "\t\033[1;33mFalsche Eingabe ! [ 1 = PHP-FPM ; 2 = mod_fcgid , 3 = mod_php, 4 =suEXEC, 5 = static, 6 = redirect, 7 = parke]\033[m" echo -e "\t\033[1;33mFalsche Eingabe ! [ 1 = PHP-FPM ; 2 = mod_fcgid , 3 = mod_php, 4 =suEXEC, 5 = static, 6 = redirect, 7 = parke, 8 = static/SFTP]\033[m"
echo "" echo ""
echononl "Your choice: " echononl "Your choice: "
;; ;;
@@ -535,8 +556,13 @@ else
_type_msg="mod_php (Apache PHP Module)" _type_msg="mod_php (Apache PHP Module)"
_new_extension=mod_php _new_extension=mod_php
elif [ "$_type" = "STATIC" ]; then elif [ "$_type" = "STATIC" ]; then
if $_sftp_chroot ; then
_type_msg="static site with suEXEC (chrooted SFTP access)"
_new_extension=static-suexec
else
_type_msg="static site (No PHP engine enabled)" _type_msg="static site (No PHP engine enabled)"
_new_extension=static _new_extension=static
fi
elif [ "$_type" = "REDIRECT" ]; then elif [ "$_type" = "REDIRECT" ]; then
_type_msg="only redirect to another site" _type_msg="only redirect to another site"
_new_extension=redirect _new_extension=redirect
@@ -1671,19 +1697,17 @@ if $_https && [[ -z "$_https_only" ]]; then
fi fi
if [ "$_type" = "FCGID" ]; then if $_suEXEC ; then
echo "" echo ""
echo "" echo ""
echo -e "\033[33m--\033[m" echo -e "\033[33m--\033[m"
echo"" echo""
#echo -e "Use a common (existing) FCGID-configuration?" if $_sftp_chroot ; then
#echo "" echo "The suEXEC user is also the (chrooted) SFTP user for this site."
#echo -e "\033[1;33m--\033[m" echo -e "Its home directory (and SFTP chroot) will be \"\033[1m$_web_base_dir\033[m\"."
#echo "" echo ""
#echo "" fi
OK=""
if $_suEXEC ; then
echononl "suEXEC User: " echononl "suEXEC User: "
read suEXEC_user read suEXEC_user
while [ "X$suEXEC_user" = "X" ]; do while [ "X$suEXEC_user" = "X" ]; do
@@ -1723,9 +1747,21 @@ if [ "$_type" = "FCGID" ]; then
set_suEXEC_password=true set_suEXEC_password=true
else else
suEXEC_password=false suEXEC_password=false
set_suEXEC_password=false
fi fi
fi # if $_suEXEC
if [ "$_type" = "FCGID" ]; then
OK=""
if $_suEXEC ; then
_COMMON_FCGI_CONFIG=false _COMMON_FCGI_CONFIG=false
else else
echo ""
echo ""
echo -e "\033[33m--\033[m"
echo""
if [ -n "$_COMMON_FCGID_CONFIG_PATH" -a -d "$_COMMON_FCGID_CONFIG_PATH" ] ; then if [ -n "$_COMMON_FCGID_CONFIG_PATH" -a -d "$_COMMON_FCGID_CONFIG_PATH" ] ; then
if [ "$_auto" = "auto" -o "$_auto" = "full-auto" ]; then if [ "$_auto" = "auto" -o "$_auto" = "full-auto" ]; then
_COMMON_FCGI_CONFIG=true _COMMON_FCGI_CONFIG=true
@@ -2041,6 +2077,10 @@ if $_print_summary ; then
echo " suEXEC User....................: $suEXEC_user" echo " suEXEC User....................: $suEXEC_user"
echo " suEXEC Group...................: $suEXEC_group" echo " suEXEC Group...................: $suEXEC_group"
fi fi
if $_sftp_chroot ; then
echo " SFTP chroot directory (home)...: $_web_base_dir"
echo " SFTP chroot group (sshd).......: $SFTP_CHROOT_GROUP"
fi
echo "" echo ""
echo "Apache Installationsverzeichnis...: $apache_base_dir ($_apache_base_dir_realpath)" echo "Apache Installationsverzeichnis...: $apache_base_dir ($_apache_base_dir_realpath)"
@@ -2377,7 +2417,14 @@ if $_suEXEC ; then
# - and docroot), so use '/usr/sbin/nologin' # - and docroot), so use '/usr/sbin/nologin'
# - # -
echononl "\tAdding User \"$suEXEC_user\".." echononl "\tAdding User \"$suEXEC_user\".."
if $_sftp_chroot ; then
# - SFTP chroot: home directory (= website's base directory) must be
# - owned by root, so don't let useradd create it ('-M').
# -
useradd -g $suEXEC_group -d $_web_base_dir -s /usr/sbin/nologin -M $suEXEC_user
else
useradd -g $suEXEC_group -d $_web_base_dir -s /usr/sbin/nologin -m $suEXEC_user useradd -g $suEXEC_group -d $_web_base_dir -s /usr/sbin/nologin -m $suEXEC_user
fi
if [ "$?" = "0" ]; then if [ "$?" = "0" ]; then
echo_ok echo_ok
else else
@@ -2397,6 +2444,83 @@ if $_suEXEC ; then
else else
echo_skipped echo_skipped
fi fi
if $_sftp_chroot ; then
echononl "\tAdding Group \"$SFTP_CHROOT_GROUP\" (chrooted SFTP users).."
if getent group $SFTP_CHROOT_GROUP > /dev/null ; then
echo_skipped
else
groupadd $SFTP_CHROOT_GROUP
if [ "$?" = "0" ]; then
echo_ok
else
echo_failed
error "Cannot create Group \"$SFTP_CHROOT_GROUP\"."
fatal
fi
fi
echononl "\tAdd user \"$suEXEC_user\" to group \"$SFTP_CHROOT_GROUP\".."
if id -nG $suEXEC_user | tr ' ' '\n' | grep -q -x "$SFTP_CHROOT_GROUP" ; then
echo_skipped
else
usermod -a -G $SFTP_CHROOT_GROUP $suEXEC_user
if [ "$?" = "0" ]; then
echo_ok
else
echo_failed
error "Cannot add user \"$suEXEC_user\" to group \"$SFTP_CHROOT_GROUP\"."
fatal
fi
fi
# - Webserver user must be able to read all files of the SFTP user
# -
# - Note: Apache children call initgroups() at startup, so the (graceful)
# - restart at the end of this script activates the new membership.
# -
echononl "\tAdd webserver user \"$web_user\" to group \"$suEXEC_group\".."
if id -nG $web_user | tr ' ' '\n' | grep -q -x "$suEXEC_group" ; then
echo_skipped
else
usermod -a -G $suEXEC_group $web_user
if [ "$?" = "0" ]; then
echo_ok
else
echo_failed
error "Cannot add user \"$web_user\" to group \"$suEXEC_group\"."
fatal
fi
fi
_suEXEC_home="$(getent passwd $suEXEC_user | cut -d ':' -f 6)"
if [[ "$(realpath -m "$_suEXEC_home")" != "$(realpath -m "$_web_base_dir")" ]]; then
warn "Home directory of user \"$suEXEC_user\" is \"$_suEXEC_home\", not \"$_web_base_dir\".\n\n\t With 'ChrootDirectory %h' SFTP access will NOT be chrooted into this site.\n\t Change it (if appropriate) with:\n\n\t usermod -d $_web_base_dir $suEXEC_user"
fi
# - Check effective sshd configuration for that user
# -
echononl "\tCheck sshd: chrooted SFTP for user \"$suEXEC_user\".."
_sshd_binary="$(command -v sshd 2> /dev/null)"
[[ -z "$_sshd_binary" ]] && [[ -x /usr/sbin/sshd ]] && _sshd_binary=/usr/sbin/sshd
if [[ -z "$_sshd_binary" ]]; then
echo_skipped
warn "sshd binary not found - cannot check sshd configuration."
_sshd_chroot_missing=true
else
_sshd_conf_eff="$($_sshd_binary -T -C user=${suEXEC_user},host=localhost,addr=127.0.0.1 2> $log_file)"
_sshd_chroot="$(echo "$_sshd_conf_eff" | awk 'tolower($1) == "chrootdirectory" {print $2}')"
_sshd_force_cmd="$(echo "$_sshd_conf_eff" | awk 'tolower($1) == "forcecommand" {$1=""; print}')"
if [[ -n "$_sshd_chroot" ]] && [[ "$_sshd_chroot" != "none" ]] \
&& [[ "$_sshd_force_cmd" =~ internal-sftp ]] ; then
echo_ok
else
echo_failed
_sshd_chroot_missing=true
fi
fi
fi
fi fi
@@ -2457,7 +2581,43 @@ else
fi fi
echononl "\tChange owner of Web Base directory \"$_web_base_dir\".." echononl "\tChange owner of Web Base directory \"$_web_base_dir\".."
if $web_base_directory_already_exists ; then if $_sftp_chroot ; then
# - SFTP chroot (sshd): The chroot directory and all its parent directories
# - must be owned by root and must not be writable by group or others.
# -
# - Note: also done, if the directory already exists - otherwise sshd
# - refuses the (chrooted) login.
# -
chown root:root $_web_base_dir && chmod 755 $_web_base_dir
if [ "$?" = "0" ]; then
echo_ok
else
echo_failed
error "Cannot change owner/permissions of web base directory \"$_web_base_dir\""
fatal
fi
echononl "\tCheck SFTP chroot path \"$_web_base_dir\".."
_chroot_path="$(realpath $_web_base_dir)"
_chroot_path_failed=""
while [[ -n "$_chroot_path" ]]; do
_owner_uid="$(stat -c '%u' "$_chroot_path")"
_perms="$(stat -c '%a' "$_chroot_path")"
if [[ "$_owner_uid" != "0" ]] || (( 8#$_perms & 8#022 )) ; then
_chroot_path_failed="${_chroot_path_failed}\n\t $(stat -c '%A %U:%G %n' "$_chroot_path")"
fi
[[ "$_chroot_path" = "/" ]] && break
_chroot_path="$(dirname "$_chroot_path")"
done
if [[ -z "$_chroot_path_failed" ]]; then
echo_ok
else
echo_failed
warn "SFTP chroot will fail! The following directories are not owned by root\n\t or are writable by group/others:\n${_chroot_path_failed}"
fi
elif $web_base_directory_already_exists ; then
echo_skipped echo_skipped
else else
if $_suEXEC ; then if $_suEXEC ; then
@@ -2515,7 +2675,17 @@ echononl "\tChange owner of \"DocumentRoot\" directory.."
if $web_base_directory_already_exists ; then if $web_base_directory_already_exists ; then
echo_skipped echo_skipped
else else
if $_suEXEC ; then if $_sftp_chroot ; then
# - Owned by the SFTP user and its (suEXEC) group. The webserver user is
# - member of that group, so apache can read all files of the user.
# -
# - Note: Using the user's own group (instead of the webserver group) is
# - robust - files created by the user always get that group, even
# - if the setgid bit gets lost (chmod by the user), and the user
# - can chgrp them back.
# -
chown -R ${suEXEC_user}:${suEXEC_group} $_doc_root && chmod 2750 $_doc_root
elif $_suEXEC ; then
chown -R ${suEXEC_user}:$suEXEC_group $_doc_root chown -R ${suEXEC_user}:$suEXEC_group $_doc_root
elif [[ "$_type" = "PHP-FPM" ]]; then elif [[ "$_type" = "PHP-FPM" ]]; then
chown -R ${unix_socket_owner}:${unix_socket_group} $_doc_root chown -R ${unix_socket_owner}:${unix_socket_group} $_doc_root
@@ -2556,6 +2726,20 @@ else
echo_skipped echo_skipped
fi fi
# - SFTP chroot: let the SFTP user read (but not write) the logfiles of the site.
# - (Apache opens the logfiles as root.)
# -
if $_sftp_chroot && [[ "$(dirname "$(realpath -m $_log_dir)")" = "$(realpath -m $_web_base_dir)" ]]; then
echononl "\tChange owner/permissions of Logfile directory (root:${suEXEC_group} 750).."
chown root:${suEXEC_group} $_log_dir && chmod 750 $_log_dir
if [ "$?" = "0" ]; then
echo_ok
else
echo_failed
error "Cannot change owner/permissions of directory \"$_log_dir\""
fi
fi
if [ "$_type" = "FCGID" -a "$_COMMON_FCGI_CONFIG" = "false" ]; then if [ "$_type" = "FCGID" -a "$_COMMON_FCGI_CONFIG" = "false" ]; then
@@ -3432,8 +3616,13 @@ EOF
if [ "$?" = "0" ];then if [ "$?" = "0" ];then
echo_ok echo_ok
if $_sftp_chroot ; then
echononl "\tChange ownerchip (${suEXEC_user}:${suEXEC_group}) of \"index.html\".."
chown ${suEXEC_user}:$suEXEC_group ${_doc_root}/index.html && chmod 640 ${_doc_root}/index.html
else
echononl "\tChange ownerchip (${web_user}:${web_group}) of \"index.html\".." echononl "\tChange ownerchip (${web_user}:${web_group}) of \"index.html\".."
chown ${web_user}:$web_group ${_doc_root}/index.html chown ${web_user}:$web_group ${_doc_root}/index.html
fi
if [ "$?" = "0" ];then if [ "$?" = "0" ];then
echo_ok echo_ok
else else
@@ -3506,6 +3695,38 @@ if $_syntax_ok ; then
fi fi
fi fi
if $_sftp_chroot && $_sshd_chroot_missing ; then
warn "sshd is NOT configured for chrooted SFTP of user \"$suEXEC_user\"!
\t Add the following block at the END of /etc/ssh/sshd_config
\t (Match blocks in files included at the top of sshd_config, i.e.
\t /etc/ssh/sshd_config.d/*.conf, may affect the following settings):
\t \033[1mMatch Group ${SFTP_CHROOT_GROUP}
\t ChrootDirectory %h
\t ForceCommand internal-sftp -u 0027
\t AllowTcpForwarding no
\t AllowAgentForwarding no
\t X11Forwarding no
\t PermitTunnel no
\t PermitTTY no
\t #PasswordAuthentication yes\033[m
\t Check the configuration and reload sshd:
\t sshd -t && systemctl reload ssh
\t sshd -T -C user=${suEXEC_user},host=localhost,addr=127.0.0.1 | grep -i -E '^(chrootdirectory|forcecommand)'
\t Note: 'AllowUsers'/'AllowGroups' (if used) must permit the user."
fi
if $_sftp_chroot && ! grep -q -r 'fix_sftp_site_permissions' /etc/cron.d /etc/crontab /var/spool/cron 2> /dev/null ; then
info "SFTP clients may set permissions apache cannot read (i.e. 600). To repair
\t them automatically, install a cronjob, i.e. /etc/cron.d/fix_sftp_site_permissions:
\t */10 * * * * root ${script_base_dir}/fix_sftp_site_permissions.sh"
fi
rm -f $log_file rm -f $log_file
echo echo
+506
View File
@@ -0,0 +1,506 @@
#!/usr/bin/env bash
# ----------
# - Repair permissions of static websites with chrooted SFTP access
# - (vhost type "static site with suEXEC (chrooted SFTP access)", vhost
# - configuration files '*.static-suexec', see create_vhost.sh).
# -
# - The webserver user is member of the suEXEC group of each such site. So
# - apache can deliver every file of the suEXEC user, as long as the file
# - has the suEXEC group and is group readable (directories: group readable
# - and executable).
# -
# - SFTP clients may break that (explicit chmod, 'preserve permissions' on
# - upload). This script repairs it:
# -
# - files : owned by suEXEC user --> group <suexec group>, g+r
# - directories: owned by suEXEC user --> group <suexec group>, u+rx,g+rx
# -
# - Security note:
# - All changes inside the DocumentRoot are done AS THE SUEXEC USER (runuser),
# - never as root. So a user cannot trick this script (i.e. by replacing a
# - file with a symlink to /etc/shadow) into changing files outside of his
# - own ones.
# -
# - Intended to run via cron, i.e. /etc/cron.d/fix_sftp_site_permissions:
# -
# - */10 * * * * root /path/to/fix_sftp_site_permissions.sh
# -
# - Without terminal, output is only produced if something was changed or
# - something went wrong (no cron mails otherwise).
# ----------
script_name="$(basename $(realpath $0))"
script_dir="$(dirname $(realpath $0))"
log_file="$(mktemp)"
lock_file="/run/lock/${script_name%.sh}.lock"
vhost_extension="static-suexec"
declare -a site_conf_arr
# =============
# --- Some functions
# =============
usage() {
[[ -n "$1" ]] && error "$1"
echo -e "
\033[1mUsage:\033[m
$(basename $0) [-h] [-n] [-v] [-d <vhost-directory>]
\033[1mDescription\033[m
Repairs group ownership and group permissions inside the DocumentRoot of
all active vhosts of type '*.${vhost_extension}' (static site with suEXEC,
chrooted SFTP access), so apache can deliver all files of the suEXEC user.
Only files/directories owned by the suEXEC user are touched. Changes are
done as the suEXEC user, not as root.
Without terminal (cron), output is only produced, if something was changed
or went wrong.
\033[1mOptions\033[m
-d <vhost-directory>
Directory containing the vhost configurations.
Default: <ServerRoot>/conf/vhosts
-h
Prints this help.
-n
Dry-run: only print what would be changed.
-v
Verbose: print every changed file/directory.
\033[1mExample:\033[m
$(basename $0) -n -v
Cronjob (/etc/cron.d/fix_sftp_site_permissions):
*/10 * * * * root $(realpath $0)
"
clean_up 1
}
clean_up() {
# Perform program exit housekeeping
rm -f $log_file
blank_line
exit $1
}
echononl(){
if $terminal ; then
echo -e -n "$*" 1>&2
fi
}
echo_ok() {
if $terminal ; then
echo -e "\033[75G[ \033[32mok\033[m ]"
fi
}
echo_failed(){
if $terminal ; then
echo -e "\033[75G[ \033[1;31mfailed\033[m ]"
fi
}
echo_skipped() {
if $terminal ; then
echo -e "\033[75G[ \033[37mskipped\033[m ]"
fi
}
fatal (){
echo ""
echo ""
if $terminal ; then
echo -e "\t[ \033[31m\033[1mFatal\033[m ]: \033[37m\033[1m$*\033[m"
echo ""
echo -e "\t\033[31m\033[1m Script will be interrupted..\033[m\033[m"
else
echo "fatal: $*"
echo "Script will be interrupted.."
fi
clean_up 1
}
error(){
echo ""
if $terminal ; then
echo -e "\t[ \033[31m\033[1mFehler\033[m ]: $*"
else
echo -e "Error: $*"
fi
echo ""
}
warn (){
echo ""
if $terminal ; then
echo -e "\t[ \033[33m\033[1mWarning\033[m ]: $*"
else
echo -e "Warning: $*"
fi
echo ""
}
info (){
if $terminal ; then
echo ""
echo -e "\t[ \033[32m\033[1mInfo\033[m ]: $*"
echo ""
fi
}
blank_line() {
if $terminal ; then
echo ""
fi
}
# - Message for a site: in terminal mode right below the site line, without
# - terminal prefixed with the site name (cron mail).
# -
site_msg() {
if $terminal ; then
echo -e " $*"
else
# - no color codes in cron mails
echo -e "[${_site}] $*" | sed 's/\x1b\[[0-9;]*m//g'
fi
}
# - Print list of changed objects (verbose mode)
# -
print_list() {
local _line
while IFS='' read -r _line ; do
[[ -z "$_line" ]] && continue
site_msg " $_line"
done < "$1"
}
# ----------
# - Jobhandling
# ----------
# - Run 'clean_up' for signals SIGHUP SIGINT SIGTERM
# -
trap clean_up SIGHUP SIGINT SIGTERM
# ----------
# - Some checks ..
# ----------
# - Running in a terminal?
# -
if [[ -t 1 ]] ; then
terminal=true
else
terminal=false
fi
# - Read commandline options
# -
dry_run=false
verbose=false
_vhost_base_dir=""
while getopts d:hnv opt ; do
case $opt in
d) _vhost_base_dir="$OPTARG" ;;
h) usage ;;
n) dry_run=true ;;
v) verbose=true ;;
*) usage "Unknown option" ;;
esac
done
# - Only root can switch to the suEXEC users
# -
[[ $(id -u) -eq 0 ]] || fatal "This script must be run as root (i.e. via sudo)."
command -v runuser > /dev/null 2>&1 || fatal "Command 'runuser' (util-linux) not found."
# - find runs as the suEXEC user, which can't access i.e. '/root'
# -
cd / || fatal "Cannot change into directory '/'."
# - Don't run twice at the same time (cron)
# -
exec 9> "$lock_file" || fatal "Cannot open lock file '${lock_file}'."
if ! flock -n 9 ; then
$terminal && warn "Another instance of '${script_name}' is running - exiting."
rm -f $log_file
exit 0
fi
# ==========
# - Begin Main Script
# ==========
# ----------
# - Headline
# ----------
if $terminal ; then
echo ""
echo -e "\033[1m----------\033[m"
echo -e "\033[32m\033[1mRunning script \033[m\033[1m$script_name\033[32m .. \033[m"
echo -e "\033[1m----------\033[m"
fi
# - Determin httpd binary
# -
_httpd_binary="$(which httpd 2> /dev/null)"
if [[ -z "$_httpd_binary" ]] && [[ -x "/usr/local/apache2/bin/httpd" ]]; then
_httpd_binary="/usr/local/apache2/bin/httpd"
fi
if [[ -n "$_httpd_binary" ]] ; then
_run_cfg="$($_httpd_binary -t -D DUMP_RUN_CFG 2> /dev/null)"
fi
# - Determin webserver user (only used to check group membership)
# -
web_user="$(echo "$_run_cfg" | grep -i -E "^User" | awk '{print$2}' | cut -d '=' -f2 | tr -d '"')"
# - Determin vhost directory (if not given by option -d)
# -
if [[ -z "$_vhost_base_dir" ]] ; then
apache_base_dir="$(echo "$_run_cfg" | grep ServerRoot | awk '{print$2}' | tr -d '"')"
[[ -z "$apache_base_dir" ]] && apache_base_dir="/usr/local/apache2"
_vhost_base_dir="${apache_base_dir}/conf/vhosts"
fi
[[ -d "$_vhost_base_dir" ]] || fatal "VHost directory '${_vhost_base_dir}' not found."
# - Collect active vhost configurations of type '*.static-suexec'
# -
# - Active means: a symlink '<site>.conf' (as created by create_vhost.sh)
# - points to '<site>.conf.static-suexec'.
# -
# - Ignore subdirectory 'DELETED' and hidden files.
# -
while IFS='' read -r -d '' _link ; do
_target="$(realpath -e "$_link" 2> /dev/null)" || continue
[[ "$_target" = *.${vhost_extension} ]] || continue
[[ -f "$_target" ]] || continue
containsElement=false
for _conf in "${site_conf_arr[@]}" ; do
[[ "$_conf" = "$_target" ]] && containsElement=true && break
done
$containsElement || site_conf_arr+=("$_target")
done < <(
find "$_vhost_base_dir" -path "${_vhost_base_dir}/DELETED" -prune -o -type l ! -name '.*' -print0
)
# - No such sites is not an error - just nothing to do
# -
if [[ ${#site_conf_arr[@]} -eq 0 ]] ; then
info "No active '*.${vhost_extension}' vhosts found in '${_vhost_base_dir}' - nothing to do."
clean_up 0
fi
if $terminal ; then
echo ""
echo -e " \033[32m\033[1mParameter Summary:\033[m"
echo ""
echo " Apache VHost directory.............: $_vhost_base_dir"
echo " Webserver user.....................: ${web_user:-unknown}"
echo " Number of sites (*.${vhost_extension}).: ${#site_conf_arr[@]}"
echo " Dry-run............................: $dry_run"
echo " Verbose............................: $verbose"
echo ""
echo ""
echo -e " \033[32m-----\033[m"
echo -e " \033[1mMain part of script ..\033[m"
echo -e " \033[32m-----\033[m"
echo ""
fi
_list_dirs="$(mktemp)"
_list_files="$(mktemp)"
_list_foreign="$(mktemp)"
declare -i _total_changed=0
declare -i _total_errors=0
for _conf in "${site_conf_arr[@]}" ; do
_site="$(basename "$_conf")"
_site="${_site%.conf.${vhost_extension}}"
echononl " Site \033[1m${_site}\033[m"
# - Read DocumentRoot and SuexecUserGroup from vhost configuration
# -
_doc_root="$(grep -m 1 -i -E '^\s*DocumentRoot\s+' "$_conf" | awk '{print$2}' | tr -d '"' | sed 's#/*$##')"
_suexec_line="$(grep -m 1 -i -E '^\s*SuexecUserGroup\s+' "$_conf")"
_user="$(echo "$_suexec_line" | awk '{print$2}' | tr -d '"')"
_group="$(echo "$_suexec_line" | awk '{print$3}' | tr -d '"')"
if [[ -z "$_doc_root" ]] || [[ -z "$_user" ]] || [[ -z "$_group" ]] ; then
echo_failed
site_msg "No DocumentRoot or no SuexecUserGroup found in '${_conf}'"
(( _total_errors++ ))
continue
fi
# - Some sanity checks before changing anything
# -
if ! getent passwd "$_user" > /dev/null ; then
echo_failed
site_msg "suEXEC user '${_user}' does not exist"
(( _total_errors++ ))
continue
fi
if ! getent group "$_group" > /dev/null ; then
echo_failed
site_msg "suEXEC group '${_group}' does not exist"
(( _total_errors++ ))
continue
fi
if [[ $(id -u "$_user") -eq 0 ]] ; then
echo_failed
site_msg "suEXEC user '${_user}' is root - refusing"
(( _total_errors++ ))
continue
fi
if [[ -L "$_doc_root" ]] || [[ ! -d "$_doc_root" ]] ; then
echo_failed
site_msg "DocumentRoot '${_doc_root}' does not exist or is a symlink"
(( _total_errors++ ))
continue
fi
if [[ "$(stat -c '%U' "$_doc_root")" != "$_user" ]] ; then
echo_failed
site_msg "DocumentRoot '${_doc_root}' is not owned by suEXEC user '${_user}'"
(( _total_errors++ ))
continue
fi
_msgs=()
# - Webserver user must be member of the suEXEC group
# -
if [[ -n "$web_user" ]] && ! id -nG "$web_user" 2> /dev/null | tr ' ' '\n' | grep -q -x "$_group" ; then
_msgs+=("\033[33mWarning:\033[m webserver user '${web_user}' is NOT member of group '${_group}'"
" Fix: usermod -a -G ${_group} ${web_user} && apachectl graceful")
fi
# - Find (and fix) wrong group/permissions - as the suEXEC user
# -
# - Directories: '-exec ... \;' runs BEFORE find descends into the
# - directory, so even directories with mode 000 will be handled.
# -
> "$_list_dirs"
> "$_list_files"
_failed=false
if $dry_run ; then
runuser -u "$_user" -- find "$_doc_root" -xdev -user "$_user" -type d \
\( ! -group "$_group" -o ! -perm -g=rx -o ! -perm -u=rx \) -print \
> "$_list_dirs" 2> "$log_file" || _failed=true
runuser -u "$_user" -- find "$_doc_root" -xdev -user "$_user" -type f \
\( ! -group "$_group" -o ! -perm -g=r \) -print \
> "$_list_files" 2>> "$log_file" || _failed=true
else
runuser -u "$_user" -- find "$_doc_root" -xdev -user "$_user" -type d \
\( ! -group "$_group" -o ! -perm -g=rx -o ! -perm -u=rx \) -print \
-exec chgrp "$_group" {} \; -exec chmod u+rx,g+rx {} \; \
> "$_list_dirs" 2> "$log_file" || _failed=true
runuser -u "$_user" -- find "$_doc_root" -xdev -user "$_user" -type f \
\( ! -group "$_group" -o ! -perm -g=r \) -print \
-exec chgrp "$_group" {} + -exec chmod g+r {} + \
> "$_list_files" 2>> "$log_file" || _failed=true
fi
declare -i _num_dirs=$(grep -c . "$_list_dirs")
declare -i _num_files=$(grep -c . "$_list_files")
# - Objects not owned by the suEXEC user (not touched, only reported)
# -
find "$_doc_root" -xdev ! -user "$_user" ! -type l -print > "$_list_foreign" 2> /dev/null
declare -i _num_foreign=$(grep -c . "$_list_foreign")
if $_failed ; then
echo_failed
(( _total_errors++ ))
elif [[ $_num_dirs -gt 0 ]] || [[ $_num_files -gt 0 ]] || [[ ${#_msgs[@]} -gt 0 ]] ; then
$dry_run && echo_skipped || echo_ok
else
echo_ok
fi
if [[ $_num_dirs -gt 0 ]] || [[ $_num_files -gt 0 ]] ; then
if $dry_run ; then
site_msg "\033[33mDry-run:\033[m would fix ${_num_dirs} directories, ${_num_files} files (user: ${_user}, group: ${_group})"
else
site_msg "Fixed ${_num_dirs} directories, ${_num_files} files (user: ${_user}, group: ${_group})"
_total_changed+=$(( _num_dirs + _num_files ))
fi
if $verbose ; then
print_list "$_list_dirs"
print_list "$_list_files"
fi
fi
for _msg in "${_msgs[@]}" ; do
site_msg "$_msg"
done
if $_failed ; then
while IFS='' read -r _line ; do
site_msg "\033[31mError:\033[m $_line"
done < <(sort -u "$log_file")
fi
# - Only in terminal mode / verbose: files not owned by the suEXEC user
# - would produce a cron mail on every run otherwise.
# -
if [[ $_num_foreign -gt 0 ]] && ( $terminal || $verbose ) ; then
site_msg "\033[33mNote:\033[m ${_num_foreign} objects in DocumentRoot are NOT owned by '${_user}' (not touched)"
$verbose && print_list "$_list_foreign"
fi
done
rm -f "$_list_dirs" "$_list_files" "$_list_foreign"
# ----------
# - Some post-script tasks ..
# ----------
if [[ $_total_errors -gt 0 ]] ; then
if $terminal ; then
error "${_total_errors} site(s) failed."
else
echo "Error: ${_total_errors} site(s) failed."
fi
clean_up 1
fi
if ! $dry_run && [[ $_total_changed -eq 0 ]] ; then
info "Nothing has changed."
fi
clean_up 0