#!/bin/bash CWP_SESSIONS_PATH=/root/.cwp_sessions function genpw { # tr -dc A-Za-z0-9 getent shadow $1 | cut -d: -f 2 } function resethash() { # currenthash=$(gethash $1) if [[ "$currenthash" != "$3" && $4 -ne 1 ]] then echo "Password has been changed since we changed it. Still restore original $1 password?" if [[ -t 0 ]] then echo "(Timeout 5 min) [y/N]?" read -t 300 answer if [[ "$answer" != "y" ]] then echo "User aborted, not restoring $1 password." return fi else echo "Lost stdin, can't ask. Restoring $1 password." fi fi echo "Restored $1 password" usermod $1 -p "$2" } function genLoginLink() { # html='
' if [[ $4 -eq 1 ]] then echo -e "$html" else base64html=$(echo "$html" | base64 | tr -d "\n") url="data:text/html;base64,$base64html" echo -e "$url" fi } function huphandler() { resethash $user $oldhash $newhash 0 exit 0 } user=root if ! [ -z $1 ] then user=$1 fi API=0 if [[ $2 == "API" ]] then API=1 fi APIRESET=0 if [[ $2 == "APIRESET" ]] then APIRESET=1 API=1 echo $0 $1 $2 $3 $4 if [ -z $3 ] then echo "APIRESET needs a hash to reset to" exit -1 fi if [ -z $4 ] then echo "APIRESET needs the current hash to match against" exit -1 fi oldhash=$(echo $3) newhash=$(echo $4) run=1 currentlist=$(ls $CWP_SESSIONS_PATH) timeleft=10 while [[ $run -eq 1 && $timeleft -gt 0 ]] do for file in $(ls $CWP_SESSIONS_PATH) do if ! echo "$currentlist" | grep $file -q then echo "Found new session file $file" run=0 fi done timeleft=$((timeleft - 1)) sleep 1 done resethash $user $oldhash $newhash 1 exit 0 fi if [[ ! -t 0 && API -eq 0 ]] then echo "This must be ran from an interactive shell." exit -1 fi trap "" INT trap "huphandler" HUP oldhash=$(gethash $user) newpw=$(genpw 16) echo "$newpw" | passwd $user --stdin &>/dev/null newhash=$(gethash $user) fqdn=$(hostname -f) if [[ $API -eq 0 ]] then echo "$user password set to: $newpw" echo -e "Log in at https://$fqdn:2087/\n" echo -e "Or copy the following to your address bar:\n" genLoginLink $fqdn $user $newpw 0 echo -e "\n" echo "Press enter to restore original password." echo "Password will also reset after 30 minutes or if the shell disconnects." read -t $((30*60)) pause resethash $user $oldhash $newhash 0 else run=1 currentlist=$(ls /root/.cwp_sessions/) genLoginLink $fqdn $user $newpw 1 systemd-run "bash" "-c" "$(realpath $0) $1 APIRESET '$oldhash' '$newhash'" &>/dev/null fi