extract_tar.py 2.08 KB
Newer Older
Julian Arni committed
1 2 3 4 5 6 7 8 9 10 11
"""
Safe version of tarfile.extractall which does not extract any files that would
be, or symlink to a file that is, outside of the directory extracted in.

Adapted from:
http://stackoverflow.com/questions/10060069/safely-extract-zip-or-tar-using-python
"""
from os.path import abspath, realpath, dirname, join as joinpath
from django.core.exceptions import SuspiciousOperation
import logging

12 13
log = logging.getLogger(__name__)

Julian Arni committed
14 15 16 17 18 19 20

def resolved(rpath):
    """
    Returns the canonical absolute path of `rpath`.
    """
    return realpath(abspath(rpath))

21

Julian Arni committed
22 23 24 25 26 27
def _is_bad_path(path, base):
    """
    Is (the canonical absolute path of) `path` outside `base`?
    """
    return not resolved(joinpath(base, path)).startswith(base)

28

Julian Arni committed
29 30 31 32 33 34 35 36
def _is_bad_link(info, base):
    """
    Does the file sym- ord hard-link to files outside `base`?
    """
    # Links are interpreted relative to the directory containing the link
    tip = resolved(joinpath(base, dirname(info.name)))
    return _is_bad_path(info.linkname, base=tip)

37

Julian Arni committed
38 39 40 41 42 43 44 45 46 47 48 49
def safemembers(members):
    """
    Check that all elements of a tar file are safe.
    """

    base = resolved(".")

    for finfo in members:
        if _is_bad_path(finfo.name, base):
            log.debug("File %r is blocked (illegal path)", finfo.name)
            raise SuspiciousOperation("Illegal path")
        elif finfo.issym() and _is_bad_link(finfo, base):
50
            log.debug("File %r is blocked: Hard link to %r", finfo.name, finfo.linkname)
Julian Arni committed
51 52 53
            raise SuspiciousOperation("Hard link")
        elif finfo.islnk() and _is_bad_link(finfo, base):
            log.debug("File %r is blocked: Symlink to %r", finfo.name,
54
                      finfo.linkname)
Julian Arni committed
55 56 57
            raise SuspiciousOperation("Symlink")
        elif finfo.isdev():
            log.debug("File %r is blocked: FIFO, device or character file",
58
                      finfo.name)
Julian Arni committed
59 60 61 62
            raise SuspiciousOperation("Dev file")

    return members

63

Julian Arni committed
64 65 66 67 68
def safetar_extractall(tarf, *args, **kwargs):
    """
    Safe version of `tarf.extractall()`.
    """
    return tarf.extractall(members=safemembers(tarf), *args, **kwargs)