Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions NEWS
Original file line number Diff line number Diff line change
@@ -1,5 +1,10 @@
1.2.3 UNRELEASED

* HARDEN: Reject unsafe tree paths in ``dulwich.archive.tar_stream``
(e.g. ``../evil``, ``.git/...``, embedded ``\`` or ``:``) instead of
emitting them as tar member names. Reported by Christopher Toth.
(Jelmer Vernooij)

* Honour ``GIT_CONFIG_COUNT`` / ``GIT_CONFIG_KEY_<n>`` /
``GIT_CONFIG_VALUE_<n>`` in porcelain entry points, via the new
opt-in ``config.env_config`` helper. (Jelmer Vernooij, #2168)
Expand Down
62 changes: 60 additions & 2 deletions dulwich/archive.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@

"""Generates tarballs for Git trees."""

__all__ = ["ChunkedBytesIO", "tar_stream"]
__all__ = ["ChunkedBytesIO", "UnsafeArchivePathError", "tar_stream"]

import posixpath
import stat
Expand All @@ -41,6 +41,56 @@
from .objects import Tree


class UnsafeArchivePathError(ValueError):
"""Raised when a tree contains a path that is unsafe to include in an archive.

Mirrors git's ``verify_path`` rejection (``error: invalid path``) for tree
entries whose names would escape the archive root or alias a special
directory on extraction. Examples include absolute paths, ``..`` or
``.git`` components, embedded backslashes, and NTFS alternate-data-stream
separators (``:``).
"""

def __init__(self, path: bytes) -> None:
"""Initialize the exception with the offending path."""
self.path = path
super().__init__(
f"unsafe path in tree: {path!r}",
)


# Characters that are never safe in a tree path destined for an archive:
# NUL terminates C strings, ``\`` is the Windows path separator (and would
# let a hostile name like ``..\evil.txt`` slip past a POSIX-only split), and
# ``:`` is the NTFS alternate-data-stream / drive-letter separator.
_UNSAFE_PATH_CHARS = (b"\x00", b"\\", b":")

_INVALID_PATH_COMPONENTS = (b".", b"..", b".git", b"")


def _is_unsafe_archive_path(path: bytes) -> bool:
"""Return True if ``path`` should not be emitted into an archive.

Matches the spirit of git's ``verify_path``: absolute paths, ``.``/``..``/
``.git`` components (case-insensitive), embedded NUL bytes, backslashes,
and colons are all rejected, regardless of host platform, because the
resulting archive may be extracted anywhere.
"""
if not path:
return True
for ch in _UNSAFE_PATH_CHARS:
if ch in path:
return True
for component in path.split(b"/"):
# Match git's protectNTFS-style normalization: trailing dots and
# spaces are stripped before comparison so ``.git.`` / ``.GIT `` are
# still recognised as ``.git`` on Windows.
normalized = component.lower().rstrip(b". ")
if normalized in _INVALID_PATH_COMPONENTS:
return True
return False


class ChunkedBytesIO:
"""Turn a list of bytestrings into a file-like object.

Expand Down Expand Up @@ -168,9 +218,17 @@ def tar_stream(
def _walk_tree(
store: "BaseObjectStore", tree: "Tree", root: bytes = b""
) -> Generator[tuple[bytes, "TreeEntry"], None, None]:
"""Recursively walk a dulwich Tree, yielding tuples of (absolute path, TreeEntry) along the way."""
"""Recursively walk a dulwich Tree, yielding tuples of (absolute path, TreeEntry) along the way.

Raises:
UnsafeArchivePathError: if a tree entry's name is unsafe to emit into
an archive (matches the spirit of git's ``verify_path`` /
``error: invalid path``).
"""
for entry in tree.iteritems():
assert entry.path is not None
if _is_unsafe_archive_path(entry.path):
raise UnsafeArchivePathError(entry.path)
entry_abspath = posixpath.join(root, entry.path)
assert entry.mode is not None
if stat.S_ISDIR(entry.mode):
Expand Down
65 changes: 64 additions & 1 deletion tests/test_archive.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,12 @@
from io import BytesIO
from unittest.mock import patch

from dulwich.archive import ChunkedBytesIO, tar_stream
from dulwich.archive import (
ChunkedBytesIO,
UnsafeArchivePathError,
_is_unsafe_archive_path,
tar_stream,
)
from dulwich.object_store import MemoryObjectStore
from dulwich.objects import Blob, Tree
from dulwich.tests.utils import build_commit_graph
Expand Down Expand Up @@ -125,6 +130,64 @@ def test_tar_stream_with_directory(self) -> None:
# Should contain the file in the subdirectory
self.assertEqual(["subdir/file.txt"], tf.getnames())

def test_unsafe_paths_rejected(self) -> None:
"""Tree entry names that git would reject as invalid are refused.

Mirrors git's ``error: invalid path`` from ``git archive`` for
absolute paths, parent-traversal, ``.git`` aliases, embedded
backslashes, and NTFS alternate-data-stream separators.
"""
# NUL is excluded here because Tree serialization uses it as a name
# terminator, so a NUL-containing name cannot be round-tripped via the
# public Tree API. _is_unsafe_archive_path still rejects it on its own.
unsafe_names = [
b"../evil.txt",
b"/absolute.txt",
b".git/hooks/pre-commit",
b"..\\evil.txt",
b".git\\hooks\\pre-commit",
b"visible.txt:hidden",
b"..",
b".git",
b".GIT",
b".Git.",
]
for name in unsafe_names:
store = MemoryObjectStore()
b1 = Blob.from_string(b"x")
store.add_object(b1)
t = Tree()
t.add(name, 0o100644, b1.id)
store.add_object(t)
with self.assertRaises(UnsafeArchivePathError, msg=repr(name)) as cm:
b"".join(tar_stream(store, t, mtime=0))
self.assertEqual(name, cm.exception.path)

def test_is_unsafe_archive_path_nul(self) -> None:
"""NUL bytes in a path are rejected even though they can't be stored in a Tree."""
self.assertTrue(_is_unsafe_archive_path(b"foo\x00bar"))
self.assertTrue(_is_unsafe_archive_path(b""))
self.assertFalse(_is_unsafe_archive_path(b"good.txt"))
self.assertFalse(_is_unsafe_archive_path(b"sub/dir/good.txt"))

def test_unsafe_path_nested_in_subtree(self) -> None:
"""A ``.git`` directory hidden under a benign parent is still rejected."""
store = MemoryObjectStore()
b1 = Blob.from_string(b"payload")
store.add_object(b1)
dotgit = Tree()
dotgit.add(b"config", 0o100644, b1.id)
store.add_object(dotgit)
root = Tree()
root.add(b"subdir", 0o040000, dotgit.id)
store.add_object(root)
# benign so far - now add a malicious sibling
outer = Tree()
outer.add(b".git", 0o040000, dotgit.id)
store.add_object(outer)
with self.assertRaises(UnsafeArchivePathError):
b"".join(tar_stream(store, outer, mtime=0))

def test_tar_stream_with_submodule(self) -> None:
"""Test tar_stream handles missing objects (submodules) gracefully."""
store = MemoryObjectStore()
Expand Down
Loading