Cover by Leonard Richardson, Lucas Carlson

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

O'Reilly logo

23.9. Normalizing Ownership and Permissions in User Directories

Problem

You want to make make sure your users' home directories don't contain world-writable directories, directories owned by other users, or other potential security problems.

Solution

Use the etc library to look up a user's home directory and UID from the username. Then use Find.find to walk the directory trees, and File methods to check and modify access to each file.

We are looking out for any case where one user's home directory can be modified by some other user. Whenever we find such a case, we fix it with a File.chmod or File.chown call. In this program, the actual calls are commented out, so that you don't accidentally change your permissions when you just want to test out the program.

	#!/usr/bin/ruby -w
	# normalize_homes.rb

	require 'etc'
	require 'find'
	require 'optparse'

	def normalize_home(pwd_entry, maximum_perms=0775, dry_run=true)
	  uid, home = pwd_entry.uid, pwd_entry.dir
	  username = pwd_entry.name

	  puts "Scanning #{username}'s home of #{home}."

	  Find.find(home) do |f|
	  next unless File.exists? f
	    stat = File.stat(f)
	    file_uid, file_gid, mode = stat.uid, stat.gid, stat.mode

The most obvious thing we want to check is whether the user owns every file in their home directory. With occasional exceptions (such as files owned by the web server), a user should own the files in his or her home directory:

 # Does the user own the file? if file_uid != uid begin current_owner = Etc.getpwuid(file_uid).name rescue ArgumentError ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required