Maintenance Ruby 3.4 gets fixes, but no new features. Switch to Ruby 4.0 →
instance method
FileUtils#remove_entry_secure
(::FileUtils::path path, ?::boolish force) -> void
remove_entry_secure(path, force = false)
lib/fileutils.rb
View on GitHub ↗
# File tmp/rubies/ruby-3.4.1/lib/fileutils.rb, line 1352
def remove_entry_secure(path, force = false)
unless fu_have_symlink?
remove_entry path, force
return
end
fullpath = File.expand_path(path)
st = File.lstat(fullpath)
unless st.directory?
File.unlink fullpath
return
end
# is a directory.
parent_st = File.stat(File.dirname(fullpath))
unless parent_st.world_writable?
remove_entry path, force
return
end
unless parent_st.sticky?
raise ArgumentError, "parent directory is world writable, FileUtils#remove_entry_secure does not work; abort: #{path.inspect} (parent directory mode #{'%o' % parent_st.mode})"
end
# freeze tree root
euid = Process.euid
dot_file = fullpath + "/."
begin
File.open(dot_file) {|f|
unless fu_stat_identical_entry?(st, f.stat)
# symlink (TOC-to-TOU attack?)
File.unlink fullpath
return
end
f.chown euid, -1
f.chmod 0700
}
rescue Errno::EISDIR # JRuby in non-native mode can't open files as dirs
File.lstat(dot_file).tap {|fstat|
unless fu_stat_identical_entry?(st, fstat)
# symlink (TOC-to-TOU attack?)
File.unlink fullpath
return
end
File.chown euid, -1, dot_file
File.chmod 0700, dot_file
}
end
unless fu_stat_identical_entry?(st, File.lstat(fullpath))
# TOC-to-TOU attack?
File.unlink fullpath
return
end
# ---- tree root is frozen ----
root = Entry_.new(path)
root.preorder_traverse do |ent|
if ent.directory?
ent.chown euid, -1
ent.chmod 0700
end
end
root.postorder_traverse do |ent|
begin
ent.remove
rescue
raise unless force
end
end
rescue
raise unless force
end
Securely removes the entry given by path, which should be the entry for a regular file, a symbolic link, or a directory.
Argument path should be interpretable as a path.
Avoids a local vulnerability that can exist in certain circumstances; see Avoiding the TOCTTOU Vulnerability.
Optional argument force specifies whether to ignore raised exceptions of StandardError and its descendants.
Related: methods for deleting.
See also
.remove_entry_secure
#remove_entry
#remove_file
#remove_dir
also in
4.1 · 4.0 · 3.3 · 3.2 · 3.1 · 3.0