CVE-2017-8291 CTF with docker and examples# Python PIL Remote Command Execution Vulnerability (GhostButt)
The PIL (Pillow) module for processing images in Python is affected by the GhostButt vulnerability (CVE-2017-8291) because it calls GhostScript internally, resulting in a remote command execution vulnerability.
## Vulnerability Summary
PIL internally determines the image type based on the image header (Magic Bytes). If it is found to be an EPS file (the header is `%!PS`), it is distributed to `PIL/EpsImagePlugin.py` for processing.
In this module, PIL calls the system's gs command, which is GhostScript, to process image files:
```Python
command = ["gs",
"-q", # quiet mode
"-g%dx%d" % size, # set output geometry (pixels)
"-r%fx%f" % res, # set input DPI (dots per inch)
"-dBATCH", # exit after processing
"-dNOPAUSE", # don't pause between pages,
"-dSAFER", # safe mode
"-sDEVICE=ppmraw", # ppm driver
"-sOutputFile=%s" % outfile, # output file
"-c", "%d %d translate" % (-bbox[0], -bbox[1]),
# adjust for image origin
"-f", infile, # input file
]
# Omit the code to determine whether GhostScript is installed
try:
with open(os.devnull, 'w+b') as devnull:
subprocess.check_call(command, stdin=devnull, stdout=devnull)
im = Image.open(outfile)
```
Although `-dSAFER`, that is, safe mode, is set, due to a sandbox bypass vulnerability in GhostScript (GhostButt CVE-2017-8291), this safe mode is bypassed and arbitrary commands can be executed.
In addition, as of now, the latest official version of GhostScript 9.21 is still affected by this vulnerability, so it can be said that as long as GhostScript is installed on the operating system, our PIL has a command execution vulnerability.
## Vulnerability Testing
Operating environment:
```
docker-compose up -d
```
After running, visit `http://your-ip:8000/` to see an upload page. The normal function is that we upload a PNG file, the backend calls PIL to load the image, and outputs the length and width. But we can change the executable command EPS file suffix to PNG for uploading, because the backend determines the image type based on the file header, so the suffix check is ignored.
For example, if we upload [poc.png](poc.png), we can execute `touch /tmp/youhavebeenpwned`. Change the command in POC to a rebound command to get a shell:
Log in to view the POC file snapshot cached by Shenlong Bot
Log in to view