Setting Apache Document Root With setgid

When you don't understand or remember the fundamental of GNU/Linux file system permissions, you'll tend to do things in an unproductive way. For example, repeatedly and explicitly update the /var/www/ folder file permissions to the Apache's group (www-data or apache).

The proper, alternative, and convenient way of setting web root, /var/www permissions are as follows:

Settings the folder permission to Apache's user group.
$ sudo chgrp apache /var/www -R
$ sudo chmod 775 /var/www -R
$ sudo chmod g+s /var/www

Allow the $USER to fully control of the web root.
$ sudo useradd -G apache $USER
$ sudo chown $USER /var/www/

Now, long grandma story. By default, the file permissions of Apache's web root directory in CentOS or Fedora are only accessible by all but writable by root user.
$ ls -l /var/www/
total 0
drwxr-xr-x 1 root root 0 Jul 23 06:31 cgi-bin/
drwxr-xr-x 1 root root 6 Oct 4 14:30 html/

Change to folder group ownership to apache user so we can install and run any web application using that user. Otherwise most web application will complain about write permissions to the folder, especially for file uploading.
$ sudo chgrp apache /var/www -R
$ ls -l /var/www/
total 0
drwxr-xr-x 1 root apache 0 Jul 23 06:31 cgi-bin/
drwxr-xr-x 1 root apache 6 Oct 4 14:30 html/

Even we've set the group ownership to apache user, any new file or folder creation will still default to root user as we're using the sudo command.
$ sudo mkdir /var/www/html/foo.d
$ sudo touch /var/www/html/foo.f
$ ls -l /var/www/html/
total 0
drwxr-xr-x 1 root root 0 Oct 4 15:03 foo.d/
rw-r--r- 1 root root 0 Oct 4 15:03 foo.f

Hence, in order to retain or inherit the group id (apache) of the parent folder in /var/www, we've to use setgid [4].
$ sudo chmod g+s /var/www/html/

Another way of setting the folder permissions using the numerical method is:
$ sudo chmod 2775 /var/www/html -R

Notice the 's' flag on the group permissions.
$ ls -ld /var/www/html
drwxr-sr-x 1 root apache 20 Oct 4 15:04 /var/www/html/

Create another folder and file in /var/www folder again. Notice the group permissions inherit the group id in /var/www.
$ sudo mkdir /var/www/html/bar.d
$ sudo touch /var/www/html/bar.f
$ ls -ltU /var/www/html
total 0
drwxr-xr-x 1 root root 0 Oct 4 15:03 foo.d/
rw-r--r- 1 root root 0 Oct 4 15:03 foo.f
drwxr-sr-x 1 root apache 0 Oct 4 15:05 bar.d/
rw-r--r- 1 root apache 0 Oct 4 15:05 bar.f

Using the namei command to show the permissions for each components in the file path.
$ namei -l /var/www/html/foo.d/
f: /var/www/html/foo.d/
drwxr-xr-x root root /
drwxr-xr-x root root var
drwxr-xr-x root apache www
drwxr-sr-x root apache html
drwxr-xr-x root root foo.d

$ namei -l /var/www/html/bar.d
f: /var/www/html/bar.d
drwxr-xr-x root root /
drwxr-xr-x root root var
drwxr-xr-x root apache www
drwxr-sr-x root apache html
drwxr-sr-x root apache bar.d

No comments:

Post a Comment