处理 Apache 文件权限的简单且安全的方法是什么?

处理 Apache 文件权限的简单且安全的方法是什么?

我尝试过为 中的文件分配不同的用户和组/var/www,但到目前为止,我尝试过的每种方法都过于复杂且容易出错。我正在寻找一种简单且可重复的模式,该模式与默认文件系统设置(权限、粘性位、ACL 等)的差别很小。一旦我确定了这一点,我计划随着时间的推移将其复制到多个服务器上。

我的情况是,我有一个 Web 应用程序/var/www/foo,需要通过 SFTP 上传。我计划让 git-ftp 进行实际上传。所有文件都需要可被 Apache 读取。某些文件夹以及应用程序创建的任何子文件夹都需要可被 Apache 写入。我在相关服务器上有一个用户帐户,目前不属于任何特殊组,但具有完全sudo访问权限。随着时间的推移,将会有多次上传,每次上传后,我都需要运行一个可能创建、修改或删除文件的脚本。

无论是在上传过程中还是在运行时,获取文件到位且不会遇到任何权限问题的最不具侵入性的方法是什么?

如果有帮助的话,我正在 Debian 上设置 Laravel 应用程序,尽管我正在寻找的模式应该能够超越该框架、它运行的语言和该分布。

答案1

首先,为了使您的权限更易于应用和维护,我建议您将数据分离到主 Web 根目录之外的位置。使用代码中的配置或符号链接指向单独的文件夹。

我们假设您担心安全问题,因此您不会使用 root 帐户进行上传。如有必要,请更新您的 Web 服务器文档根目录。

创建一个组,例如www-pub,将你用来发布代码的账户添加到该组。

  • /var/www/www.example.org/data
  • /var/www/www.example.org/www

有了这些,我通常会像这样设置权限。这些命令的编写方式应该可以安全地重复使用。

# perms for the code/html folder
find /var/www/www.example.org/www -type d ! -perm 2775 -print0 | xargs --null --no-run-if-empty chmod 2775
find /var/www/www.example.org/www -type f ! -perm 0664 -print0 | xargs --null --no-run-if-empty chmod 0664
find /var/www/www.example.org/www \( ! -user root -o ! -group www-pub \) -print0 | \
xargs --verbose --null --no-run-if-empty chown root:www-www-pub

# perms for the data folder
find /var/www/www.example.org/data -type d ! -perm 2755 -print0 | xargs --null --no-run-if-empty chmod 2755
find /var/www/www.example.org/data -type f ! -perm 0644 -print0 | xargs --null --no-run-if-empty chmod 0644
find /var/www/www.example.org/data \( ! -user www-data -o ! -group www-data \) -print0 | \
xargs --verbose --null --no-run-if-empty chown www-data:www-data

另一件重要的事情是将 shell 和 sftp 服务器的 umask 设置为 0002。如果不设置将 umask 从常用默认值 0022 更改为其他值,则写入的文件只能由组读取。但您需要它来不屏蔽组写入位。

如果您不想弄乱掩码,并且文件系统已启用 ACL,那么您可以改用 ACL,这在某种程度上简化了事情,因为当您使用 ACL 时,环境 umask 不会被视为非默认条目。

# set on empty directory before uploading files
# the parent directory has full read-write-execute for www-pub
# newly create files will be read-write for www-pub
setfacl --recursive --modify group:www-pub:rwx,default:group:www-pub:rw- /var/www/www.example.org/www

setfacl --recursive --modify group:www-data:rwx,default:group:www-data:rw- /var/www/www.example.org/data

无论如何,没有唯一正确的方法,但希望以上内容可以作为一个有用的起点。

相关内容