sudoshim.sh (2445B)
1 #!/usr/bin/env bash 2 # A wrapper around `sudo` that replaces the expected password prompt string (if given) with a bogus value. 3 # This allows testing situations where the expected password prompt is not found. 4 # This wrapper also supports becoming an intermediate user before executing sudo, to support testing as root. 5 6 set -eu 7 8 args=("${@}") 9 intermediate_user_idx='' 10 original_prompt='' 11 shell_executable='' 12 shell_command='' 13 original_prompt_idx='' 14 15 # some args show up after others, but we need them before processing args that came before them 16 for i in "${!args[@]}"; do 17 case "${args[$i]}" in 18 "-p") 19 original_prompt="${args[i+1]}" 20 original_prompt_idx="${i}" 21 ;; 22 "-c") 23 shell_executable="${args[i-1]}" 24 shell_command="${args[i+1]}" 25 ;; 26 esac 27 done 28 29 for i in "${!args[@]}"; do 30 case "${args[$i]}" in 31 "--inject-stdout-noise") 32 echo "stdout noise" 33 unset "args[i]" 34 ;; 35 "--inject-stderr-noise") 36 echo >&2 "stderr noise" 37 unset "args[i]" 38 ;; 39 "--bogus-prompt") 40 args[original_prompt_idx+1]="BOGUSPROMPT" 41 unset "args[i]" 42 ;; 43 "--intermediate-user") 44 intermediate_user_idx="${i}" 45 ;; 46 "--close-stderr") 47 >&2 echo "some injected stderr, EOF now" 48 exec 2>&- # close stderr, doesn't seem to work on Ubuntu 24.04 (either not closed or not seen in Python?) 49 unset "args[i]" 50 ;; 51 "--sleep-before-sudo") 52 sleep 3 53 unset "args[i]" 54 ;; 55 "--pretend-to-be-broken-passwordless-sudo") 56 echo '{"hello":"not a module response"}' 57 exit 0 58 ;; 59 "--pretend-to-be-broken-sudo") 60 echo -n "${original_prompt}" 61 read -rs 62 echo 63 echo "success, but not invoking given command" 64 exit 0 65 ;; 66 "--pretend-to-be-sudo") 67 echo -n "${original_prompt}" 68 read -rs 69 echo 70 echo "success, invoking given command" 71 "${shell_executable}" -c "${shell_command}" 72 exit 0 73 ;; 74 esac 75 done 76 77 if [[ "${intermediate_user_idx}" ]]; then 78 # The current user can sudo without a password prompt, so delegate to an intermediate user first. 79 intermediate_user_name="${args[intermediate_user_idx+1]}" 80 81 unset "args[intermediate_user_idx]" 82 unset "args[intermediate_user_idx+1]" 83 84 exec sudo -n -u "${intermediate_user_name}" sudo -k "${args[@]}" 85 else 86 # The current user requires a password to sudo, so sudo can be used directly. 87 exec sudo -k "${args[@]}" 88 fi