mustberoot.subr revision 240684
1if [ ! "$_MUSTBEROOT_SUBR" ]; then _MUSTBEROOT_SUBR=1
2#
3# Copyright (c) 2006-2012 Devin Teske
4# All Rights Reserved.
5#
6# Redistribution and use in source and binary forms, with or without
7# modification, are permitted provided that the following conditions
8# are met:
9# 1. Redistributions of source code must retain the above copyright
10#    notice, this list of conditions and the following disclaimer.
11# 2. Redistributions in binary form must reproduce the above copyright
12#    notice, this list of conditions and the following disclaimer in the
13#    documentation and/or other materials provided with the distribution.
14#
15# THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
16# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING BUT NOT LIMITED TO, THE
17# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
18# ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
19# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
20# DAMAGES (INLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
21# OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
22# HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
23# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
24# OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
25# SUCH DAMAGE.
26#
27# $FreeBSD: head/usr.sbin/bsdconfig/share/mustberoot.subr 240684 2012-09-18 22:28:42Z dteske $
28#
29############################################################ INCLUDES
30
31BSDCFG_SHARE="/usr/share/bsdconfig"
32. $BSDCFG_SHARE/common.subr || exit 1
33f_include $BSDCFG_SHARE/dialog.subr
34
35BSDCFG_LIBE="/usr/libexec/bsdconfig"
36f_include_lang $BSDCFG_LIBE/include/messages.subr
37
38############################################################ CONFIGURATION
39# NOTE: These are not able to be overridden/inherited for security purposes.
40
41#
42# Number of tries a user gets to enter his/her password before we log the
43# sudo(8) failure and exit.
44#
45PASSWD_TRIES=3
46
47#
48# While in SECURE mode, should authentication as `root' be allowed? Set to
49# non-NULL to enable authentication as `root', otherwise disabled.
50#
51# WARNING: 
52# Unless using a custom sudo(8) configuration, user `root' should not be
53# allowed because no password is required to become `root' when already `root'
54# and therefore, any value entered as password will work.
55#
56SECURE_ALLOW_ROOT=
57
58#
59# While in SECURE mode, should we divulge (through error message) when the
60# requested authentication user does not exist? Set to non-NULL to enable,
61# otherwise a non-existent user is treated like an invalid password.
62#
63SECURE_DIVULGE_UNKNOWN_USER=
64
65############################################################ FUNCTIONS
66
67# f_become_root_via_sudo
68#
69# If not running as root, prompt for sudo(8) credentials to become root.
70# Re-execution of the current program via sudo is automatically handled.
71#
72# The following environment variables effect functionality:
73#
74# 	USE_XDIALOG   Either NULL or Non-NULL. If given a value will indicate
75# 	              that Xdialog(1) should be used instead of dialog(1).
76#
77f_become_root_via_sudo()
78{
79	local msg hline size
80
81	[ "$( id -u )" = "0" ] && return $SUCCESS
82
83	f_have sudo || f_die 1 "$msg_must_be_root_to_execute" "$pgm"
84
85	#
86	# Check sudo(8) access before prompting for password.
87	#
88	:| sudo -S -v 2> /dev/null
89	if [ $? -ne $SUCCESS ]; then
90		#
91		# sudo(8) access denied. Prompt for their password.
92		#
93		msg="$msg_please_enter_password"
94		hline="$hline_alnum_punc_tab_enter"
95		size=$( f_dialog_inputbox_size \
96		        	"$DIALOG_TITLE"     \
97		        	"$DIALOG_BACKTITLE" \
98		        	"$msg"              \
99		        	"$hline"            )
100
101		#
102		# Continue prompting until they either Cancel, succeed
103		# or exceed the number of allowed failures.
104		#
105		local password nfailures=0 retval
106		while [ $nfailures -lt $PASSWD_TRIES ]; do
107			if [ "$USE_XDIALOG" ]; then
108				password=$( $DIALOG \
109					--title "$DIALOG_TITLE"            \
110					--backtitle "$DIALOG_BACKTITLE"    \
111					--hline "$hline"                   \
112					--ok-label "$msg_ok"               \
113					--cancel-label "$msg_cancel"       \
114					--password --inputbox "$msg" $size \
115					2>&1 > /dev/null )
116				retval=$?
117
118				# Catch X11-related errors
119				[ $retval -eq 255 ] &&
120					f_die $retval "$password"
121			else
122				$DIALOG \
123					--title "$DIALOG_TITLE"         \
124					--backtitle "$DIALOG_BACKTITLE" \
125					--hline "$hline"                \
126					--ok-label "$msg_ok"            \
127					--cancel-label "$msg_cancel"    \
128					--insecure                      \
129					--passwordbox "$msg" $size      \
130					2> "$DIALOG_TMPDIR/dialog.inputbox.$$"
131				retval=$?
132				password=$( f_dialog_inputstr )
133			fi
134
135			# Exit if the user cancelled.
136			[ $retval -eq $SUCCESS ] || exit $retval
137
138			#
139			# Validate sudo(8) credentials
140			#
141			sudo -S -v 2> /dev/null <<-EOF
142			$password
143			EOF
144			retval=$?
145			unset password # scrub memory
146			if [ $retval -eq $SUCCESS ]; then
147				# Access granted...
148				break
149			else
150				# Access denied...
151				nfailures=$(( $nfailures + 1 ))
152
153				# introduce a short delay
154				if [ $nfailures -lt $PASSWD_TRIES ]; then
155					f_dialog_info "$msg_sorry_try_again"
156					sleep 1
157				fi
158			fi
159		done
160
161		#
162		# If user exhausted number of allowed password tries, log
163		# the security event and exit immediately.
164		#
165		if [ $nfailures -ge $PASSWD_TRIES ]; then
166			msg=$( printf "$msg_nfailed_attempts" "$nfailures" )
167			logger -p auth.notice -t sudo " " \
168				"$USER : $msg" \
169				"; TTY=$(tty)" \
170				"; PWD=$PWD"   \
171				"; USER=root"  \
172				"; COMMAND=$0"
173			f_die 1 "sudo: $msg"
174		fi
175	fi
176
177	# Use xauth(1) to grant root the ability to use this X11/SSH session
178	if [ "$USE_XDIALOG" -a "$SSH_CONNECTION" -a "$DISPLAY" ]; then
179		f_have xauth || f_die 1 \
180			"$msg_no_such_file_or_directory" "$pgm" "xauth"
181		local HOSTNAME displaynum
182		HOSTNAME=$(hostname)
183		displaynum="${DISPLAY#*:}"
184		xauth -f ~/.Xauthority extract - $HOSTNAME/unix:$displaynum \
185			$HOSTNAME:$displaynum | sudo sh -c 'xauth -ivf \
186			~root/.Xauthority merge - > /dev/null 2>&1'
187	fi
188
189	# Re-execute ourselves with sudo(8)
190	if [ $ARGC -gt 0 ]; then
191		exec sudo "$0" $ARGV
192	else
193		exec sudo "$0"
194	fi
195	exit $? # Never reached unless error
196}
197
198# f_authenticate_some_user
199#
200# Only used if running as root and requires X11 (see USE_XDIALOG below).
201# Prompts the user to enter a username and password to be authenticated via
202# sudo(8) to proceed.
203#
204# The following environment variables effect functionality:
205#
206# 	USE_XDIALOG   Either NULL or Non-NULL. If given a value will indicate
207# 	              that Xdialog(1) should be used instead of dialog(1).
208#
209f_authenticate_some_user()
210{
211	local msg hline size width height
212
213	f_have sudo || f_die 1 "$msg_must_be_root_to_execute" "$pgm"
214
215	#
216	# Secure-mode has been requested.
217	#
218 
219	[ "$USE_XDIALOG" ] || f_die 1 "$msg_secure_mode_requires_x11"
220	[ "$(id -u)" = "0" ] || f_die 1 "$msg_secure_mode_requires_root"
221
222	#
223	# Prompt for sudo(8) credentials.
224	#
225
226	msg="$msg_please_enter_username_password"
227	hline="$hline_alnum_punc_tab_enter"
228	size=$( f_xdialog_2inputsbox_size \
229	        	"$DIALOG_TITLE"      \
230	        	"$DIALOG_BACKTITLE"  \
231	        	"$msg"               \
232	        	"$field_username" "" \
233	        	"$field_password" "" )
234	width="${size##*[$IFS]}"
235	height="${size%%[$IFS]*}"
236	height=$(( $height + 2 )) # Add height for --password
237
238	#
239	# Continue prompting until they either Cancel, succeed or exceed the
240	# number of allowed failures.
241	#
242	local user_pass nfailures=0 retval
243	while [ $nfailures -lt $PASSWD_TRIES ]; do
244		user_pass=$( $DIALOG \
245			--title "$DIALOG_TITLE"         \
246			--backtitle "$DIALOG_BACKTITLE" \
247			--hline "$hline"                \
248			--ok-label "$msg_ok"            \
249			--cancel-label "$msg_cancel"    \
250			--password --2inputsbox "$msg"  \
251			$height $width                  \
252			"$field_username" ""            \
253			"$field_password" ""            \
254			2>&1 > /dev/null )
255		retval=$?
256
257		# Catch X11-related errors
258		[ $retval -eq 255 ] && f_die $retval "$user_pass"
259
260		# Exit if the user cancelled.
261		[ $retval -eq $SUCCESS ] || exit $retval
262
263		#
264		# Make sure the user exists and is non-root
265		#
266		local user password
267		user="${user_pass%%/*}"
268		password="${user_pass#*/}"
269		unset user_pass # scrub memory
270		if [ ! "$user" ]; then
271			nfailures=$(( $nfailures + 1 ))
272			f_dialog_msgbox "$msg_no_username"
273			continue
274		fi
275		if [ ! "$SECURE_ALLOW_ROOT" ]; then
276			case "$user" in
277			root|toor)
278				nfailures=$(( $nfailures + 1 ))
279				f_dialog_msgbox "$( printf \
280					"$msg_user_disallowed" "$user" )"
281				continue
282			esac
283		fi
284		if ! f_quietly id "$user"; then
285			nfailures=$(( $nfailures + 1 ))
286			if [ "$SECURE_DIVULGE_UNKNOWN_USER" ]; then
287				f_dialog_msgbox "$( printf \
288					"$msg_unknown_user" "$user" )"
289			elif [ $nfailures -lt $PASSWD_TRIES ]; then
290				f_dialog_info "$msg_sorry_try_again"
291				sleep 1
292			fi
293			continue
294		fi
295
296		#
297		# Validate sudo(8) credentials for given user
298		#
299		su -m "$user" <<-EOF
300			sh <<EOS
301				sudo -k
302				sudo -S -v 2> /dev/null <<EOP
303				$password
304				EOP
305			EOS
306		EOF
307		retval=$?
308		unset user
309		unset password # scrub memory
310
311		if [ $retval -eq $SUCCESS ]; then
312			# Access granted...
313			break
314		else
315			# Access denied...
316			nfailures=$(( $nfailures + 1 ))
317
318			# introduce a short delay
319			if [ $nfailures -lt $PASSWD_TRIES ]; then
320				f_dialog_info "$msg_sorry_try_again"
321				sleep 1
322			fi
323		fi
324	done
325
326	#
327	# If user exhausted number of allowed password tries, log
328	# the security event and exit immediately.
329	#
330	if [ $nfailures -ge $PASSWD_TRIES ]; then
331		msg=$( printf "$msg_nfailed_attempts" "$nfailures" )
332		logger -p auth.notice -t sudo " " \
333			"${SUDO_USER:-$USER} : $msg" \
334			"; TTY=$(tty)"               \
335			"; PWD=$PWD"                 \
336			"; USER=root"                \
337			"; COMMAND=$0"
338		f_die 1 "sudo: $message"
339	fi
340}
341
342# f_mustberoot_init
343#
344# If not already root, make the switch to root by re-executing ourselves via
345# sudo(8) using user-supplied credentials.
346#
347# The following environment variables effect functionality:
348#
349# 	SECURE        Either NULL or Non-NULL. If given a value will indicate
350# 	              that (while running as root) sudo(8) authentication is
351# 	              required to proceed.
352#
353f_mustberoot_init()
354{
355	if [ "$(id -u)" != "0" -a ! "$SECURE" ]; then
356		f_become_root_via_sudo
357	elif [ "$SECURE" ]; then
358		f_authenticate_some_user
359	fi
360}
361
362fi # ! $_MUSTBEROOT_SUBR
363