# Copyright 1999-2018 Gentoo Foundation
# Distributed under the terms of the GNU General Public License v2

bad_bin_group_write_check() {
	# Warn about globally-installed executables (in /bin, /usr/bin, /sbin,
	# /usr/sbin, or /opt/bin) that are group-writable by a nonzero GID.

	# This check doesn't work on non-root prefix installations at
	# the moment, because every executable therein is owned by a
	# nonzero GID.
	[[ "${EUID}" -ne "0" || "${PORTAGE_INST_UID}" -ne "0" ]] && return

	local d f found=()

	for d in "${ED%/}/opt/bin" "${ED%/}/bin"  "${ED%/}/usr/bin" \
							   "${ED%/}/sbin" "${ED%/}/usr/sbin"; do
		[[ -d "${d}" ]] || continue

		# Read the results of the "find" command into the "found" array.
		#
		# Use -L to catch symlinks whose targets are vulnerable,
		# even though it won't catch ABSOLUTE symlinks until the package
		# is RE-installed (the first time around, the target won't exist).
		#
		# We match the GID and not the name "root" here because (for
		# example) on FreeBSD, the superuser group is "wheel".
		#
		# We don't make an exception for setguid executables here, because
		# a group-writable setguid executable is likely a mistake. By
		# altering the contents of the executable, a member of the group
		# can allow everyone (i.e. the people running it) to obtain the
		# full privileges available to that group. While only existing
		# group members can make that choice, it's a decision usually
		# limited to the system administrator.
		while read -r -d '' f; do
			found+=( "${f}" )
		done < <(find -L "${d}"   \
					-maxdepth 1   \
					-type f       \
					-perm /g+w    \
					! -gid 0      \
					-print0)
	done

	if [[ ${found[@]} ]]; then
		eqawarn "system executables group-writable by nonzero gid:"
		for f in "${found[@]}"; do
			# Strip off the leading destdir before outputting the path.
			eqawarn "  ${f#${D%/}}"
		done
	fi
}

bad_bin_group_write_check
:
