#!/bin/bash chdir=0 kerberos=0 x11=0 while getopts ":kx" opt; do case $opt in c) chdir=1;; k) kerberos=1;; x) x11=1;; esac done shift $((OPTIND-1)) user="$1"; shift if [ -z "$user" ]; then echo >&2 "Usage: become [-c] [-k] [-x] " echo >&2 "Options: -c Stay in current directory even if target user is not root." echo >&2 " -k Delegate Kerberos credentials even if target user is not root." echo >&2 " -x Delegate X11 cookie even if target user is not root." exit 1 fi uid=$(PATH=/usr/xpg4/bin:/usr/bin id -u "$user" 2>/dev/null) if [ -z "$uid" ]; then echo >&2 "Who is $user?" exit 2 fi if [ $uid = 0 ]; then chdir=1 kerberos=1 x11=1 fi PRINCIPAL=$(klist 2>/dev/null | sed -n 's/^Default principal: //p') if [ $x11 = 1 -a -n "$DISPLAY" -a "${DISPLAY##localhost:}" = "$DISPLAY" ]; then COOKIE="$(xauth list $DISPLAY)" fi ignore_profile_user=0 for candidate in "$HOME" "$PROFILE_HOME"; do [ -n "$candidate" ] || continue BECOME="$candidate/.become" [ -d "$BECOME" ] || continue # Script to run when becoming any user. [ -z "$allusersprofile" ] && allusersprofile="$BECOME/all" [ -f "$allusersprofile" ] || allusersprofile= # Set $HOME/all sticky to ignore $PROFILE_HOME/$user. if [ "$candidate" = "$HOME" ]; then [ -k "$BECOME/all" ] && ignore_profile_user=1 else [ $ignore_profile_user = 1 ] && continue fi # Script to run (after the one mentioned above) when becoming this user. [ -z "$userprofile" ] && userprofile="$BECOME/$user" [ -f "$userprofile" ] || userprofile= done file="${TMPDIR:-/tmp}/$USER.become.$user.$RANDOM.$$" umask=$(builtin umask -p) builtin umask 077 if exec 3>"$file" && exec <"$file" && rm "$file"; then builtin $umask echo >&3 "cd" echo >&3 "PROFILE_HOME='${PROFILE_HOME:-$HOME}'" if [ -n "$PRINCIPAL" ]; then echo >&3 "PRINCIPAL='$PRINCIPAL'" if [ $kerberos = 1 ]; then ccname=$(klist 2>/dev/null | sed -n 's/^Ticket cache: [DF]I[LR][E:]://p') if [ -f "$ccname" ]; then echo >&3 "export KRB5CCNAME='$KRB5CCNAME'" openssl=$(find_working openssl) if [ -n "$openssl" ]; then echo >&3 "KRB5OPENSSL='$openssl'" echo >&3 "KRB5BASE64='$($openssl enc -a -in $ccname)'" fi fi fi fi if [ -n "$DISPLAY" -a -n "$COOKIE" ]; then echo >&3 "xauth add $COOKIE" else echo >&3 "unset DISPLAY" fi if [ ! "$PROFILE_HOME" = "$HOME" ]; then echo >&3 "export SCREENRC=$PROFILE_HOME/.screenrc" fi else exit 111 fi echo >&3 ". ${PROFILE_HOME:-$HOME}/.bash_profile" [ -f "$allusersprofile" ] && cat >&3 2>/dev/null "$allusersprofile" [ -f "$userprofile" ] && cat >&3 2>/dev/null "$userprofile" [ $chdir = 1 ] && echo >&3 2>/dev/null "cd - &>/dev/null" exec 3>&- dir=$(dirname "$0") [ "$dir" = "." ] && dir="$PWD" exec sudo -H -u "$user" "$dir/became" exit 111