Safely extract zip or tar using Python

后端 未结 4 1118
感动是毒
感动是毒 2020-12-15 04:03

I\'m trying to extract user-submitted zip and tar files to a directory. The documentation for zipfile\'s extractall method (similarly with tarfile\'s extractall) states that

4条回答
  •  醉梦人生
    2020-12-15 05:04

    Contrary to the popular answer, unzipping files safely is not completely solved as of Python 2.7.4. The extractall method is still dangerous and can lead to path traversal, either directly or through the unzipping of symbolic links. Here was my final solution which should prevent both attacks in all versions of Python, even versions prior to Python 2.7.4 where the extract method was vulnerable:

    import zipfile, os
    
    def safe_unzip(zip_file, extractpath='.'):
        with zipfile.ZipFile(zip_file, 'r') as zf:
            for member in zf.infolist():
                abspath = os.path.abspath(os.path.join(extractpath, member.filename))
                if abspath.startswith(os.path.abspath(extractpath)):
                    zf.extract(member, extractpath)
    

    Edited: Fixed variable name clash. Thanks Juuso Ohtonen.

提交回复
热议问题