Easy permission sanitizing using chmod

Let’s say you have a web app, such as WordPress, and you have installed it on your own server. You are of course security conscious, so you wish to have the permissions set up correctly, no exceptions. this usually means 755 (rwxr-xr-x) for directories and 644 (rw-r–r–) for files.

The way I used to solve this, on every server I worked, I set up a small shell script (sanitize-perms.sh) along the lines of:

#!/bin/sh
TARGET=$1
find $TARGET -type f | xargs chmod 0644
find $TARGET -type d | xargs chmod 0755

This worked well, with one huge caveat: What if you, somewhere in that directory structure had a file which needed to be executable?

I don’t know if such a case exists in WordPress, I’ve used that script on a couple of WP installations without any noticeable side-effects, but it’s obviously a flawed approach.

I’ll side-track this post a bit, since it is relevant to the overall post, that I, through identi.ca, stumbled upon this blog post (which is awesome by the way, go read it!) about why LaTeX is so cool, and why it can be useful writing your résumé using it.

Just by chance I continued into Dan’s code section, and long story short, I found some cool stuff in his .bashrc file. Most notably this little beauty:

# sanitize - set file/directory owner and permissions to normal values (644/755)
# Usage: sanitize <file>
sanitize() {
	chmod -R u=rwX,go=rX "$@"
	chown -R ${USER}.users "$@"
}

I personally, for some reason, have always tended more to the octal representation than the [ugo][+-=][rwx] syntax, but that single chmod line is so outstandingly brilliant that I am almost forced to switch.

In one fell swoop Dan’s command does what I need two commands (really, with the xargs and I suppose one new process per found file/directory to execute chmod, my script needs a lot of processes) to accomplish.

The magic happens in that capital X, which is defined in the chmod man-file as: “execute/search only  if  the file is a directory or already has execute permission for some user”.

Directories automatically receives the executable flag, and any file which already has it, maintains it. Bloody brilliant!

Many thanks to Dan for sharing his configuration files, one of these days I’ll have to follow his good example.

Related posts:

  1. fsniper fsniper is one of those really neat tools I’ve found...
  2. Easy identification of USB storage disks I have during the last couple of weeks begun the...
  3. 2011w35 I guess the first big thing to happen this week,...
  4. Whitespaces in filenames and how to get rid of them Although it has been more than four years since I...
  5. 2011w30 Hacking the shell I’ve scratched some itches this week, some...

Related posts brought to you by Yet Another Related Posts Plugin.

Tags: , , , ,

Comments are closed.