Bash and Linux

Find world-writable files

mediumDisk, processes, permissions

Problem statement

A security scan flagged the server for world-writable files, which any local user can modify. List every regular file under app/ that has the 'others' write bit set, sorted. Then list world-writable directories separately. Recreate the tree with (Linux; file permissions do not apply on Windows filesystems):

Bash
umask 022
mkdir -p app/config app/uploads app/bin
echo 'db_host=10.0.0.4' > app/config/db.conf && chmod 644 app/config/db.conf
echo 'API_TOKEN=changeme' > app/config/secrets.env && chmod 666 app/config/secrets.env
printf '#!/bin/sh\necho run\n' > app/bin/run.sh && chmod 777 app/bin/run.sh
printf '#!/bin/sh\necho help\n' > app/bin/helper.sh && chmod 755 app/bin/helper.sh
echo 'png' > app/uploads/avatar.png && chmod 664 app/uploads/avatar.png
chmod 777 app/uploads

Examples

Example 1

Input: find app -type f -perm -0002 | sort

Output: app/bin/run.sh app/config/secrets.env

Explanation: Mode 777 and 666 both include the others-write bit; 664 and 755 do not.

Example 2

Input: find app -type d -perm -0002

Output: app/uploads

Hints

Approach

Optimal

-type f restricts the search to regular files. -perm -0002 uses the leading - to mean 'all of these bits are set', and 0002 is the write bit for others, so any mode with that bit (666, 777, 772...) matches regardless of the other bits. sort gives stable output. To audit a whole server, start at /, add -xdev so find does not wander into /proc, network mounts or other filesystems, and send permission errors to /dev/null.

Bash
# Audit a whole server (stay on one filesystem, hide permission errors):
# find / -xdev -type f -perm -0002 2>/dev/null
find app -type f -perm -0002 | sort

Follow-up questions

  • How would you fix every file found in one command? (-exec chmod o-w {} +)
  • How would you also find SUID binaries? (-perm -4000)

Frequently asked questions

-perm 0002 matches only files whose mode is exactly 0002. -perm -0002 matches when all the listed bits are set, which is what you want here. -perm /0002 matches when any of the listed bits are set; with a single bit it behaves the same as -, but differs for masks like /0022 (group or others writable).

Not if it has the sticky bit, like /tmp (mode 1777): anyone can create files, but only the owner can delete or rename them. A world-writable directory without the sticky bit lets any user delete other users' files. Find those with find / -xdev -type d -perm -0002 ! -perm -1000.