﻿id	summary	reporter	owner	description	type	status	component	version	severity	resolution	keywords	cc	stage	has_patch	needs_docs	needs_tests	needs_better_patch	easy	ui_ux
37568	Harden django.utils.archive and TemplateCommand extraction (permission mask, pre-validation, special ZIP entries, streaming)	VCoder101		"As suggested during the review of #37390, this ticket tracks permission masking and closely related extraction hardening in `django/utils/archive.py` and `django/core/management/templates.py`, without overlapping #37390 (PR #22116, special tar members) or #36588 (PR #21843, `--size-limit` header check).

### Issues observed on `main` (`5b0c26e7`)

1. **Special permission bits preserved (`CWE-276` / `CWE-732`):**
   - `BaseArchive._copy_permissions()` (`django/utils/archive.py:108-115`) calls `os.chmod(filename, mode)` directly without masking `0o777`, preserving `setuid` (`0o4000`), `setgid` (`0o2000`), and `sticky` (`0o1000`) bits on both TAR and ZIP entries (and passing `S_IFMT` bits through).
   - `TemplateCommand.apply_umask()` (`django/core/management/templates.py:392-396`) uses `stat.S_IMODE(os.stat(old_path).st_mode)` without `& 0o777`, preserving `setuid`/`setgid`/`sticky` bits when copying from local `--template` directories.

2. **Partial writes before `SuspiciousOperation`:**
   - Both `TarArchive.extract()` and `ZipArchive.extract()` validate each member's `target_filename()` inline during the write loop. If an archive contains `tpl/good.txt` followed by `tpl/../../escape.txt`, `good.txt` is written to disk before extraction aborts.

3. **Non-regular ZIP entries extracted silently:**
   - `ZipArchive.extract()` does not inspect `stat.S_IFMT(info.external_attr >> 16)`. Symlinks (`S_IFLNK`), FIFOs (`S_IFIFO`), devices (`S_IFCHR`/`S_IFBLK`), and sockets (`S_IFSOCK`) are extracted as regular files containing the link target / payload.

4. **Unbounded in-memory reads during ZIP extraction and template download:**
   - `ZipArchive.extract()` calls `self._archive.read(name)` **before** validating `target_filename(to_path, name)`, buffering the entire decompressed member in memory even for invalid paths.
   - `TemplateCommand.download()` (`django/core/management/templates.py:328`) calls `target.write(source.read())` instead of streaming via `shutil.copyfileobj()`.

5. **`UnboundLocalError` on broken symlinks in `TarArchive.extract()`:**
   - If `self._archive.extractfile(member)` raises `KeyError`/`AttributeError` (e.g. a broken symlink in a tar archive), `finally: if extracted:` raises `UnboundLocalError` because `extracted` is never initialized before `try:`.

### Proposed changes

1. Mask permissions with `& 0o777` in `BaseArchive._copy_permissions()` and `TemplateCommand.apply_umask()`.
2. Pre-validate all member target paths (and ZIP POSIX file types) before creating any directories or writing files.
3. In `ZipArchive.extract()`, reject POSIX file types other than `0` (DOS/no POSIX mode), `stat.S_IFREG`, and `stat.S_IFDIR` with `SuspiciousOperation(f""Archive contains special file: '{orig_name}'"")`.
4. Stream `ZipArchive.extract()` using `self._archive.open(info)` + `shutil.copyfileobj()`, and stream `TemplateCommand.download()` using `shutil.copyfileobj(source, target)`. Call `_copy_permissions()` after closing the output file.
5. Initialize `extracted = None` before `try:` in `TarArchive.extract()`.

### Relationship to open tickets

- **#37390 (PR #22116):** filters non-`(isfile|issym|islnk)` members in `TarArchive`. Not modified here (if PR #22116 merges first, rebasing the `TarArchive.extract()` loop is trivial).
- **#36588 (PR #21843):** adds a `--size-limit` cap. Not modified here; streaming `ZipArchive.extract()` and `download()` complements it.

If reviewers prefer keeping permission masking separate from path pre-validation / ZIP special files / streaming, I am happy to split this into two smaller linked tickets (e.g., (1) `0o777` masking in `_copy_permissions()` + `apply_umask()`, and (2) atomic pre-validation + ZIP special-file rejection + streaming + `extracted = None`).

### Verification

A draft patch with 7 new regression tests in `tests/utils_tests/test_archive.py` was tested on `main@5b0c26e7` (Python 3.13.18):
- Before patch: `utils_tests.test_archive` → `Ran 11 tests — FAILED (failures=10, errors=1)`.
- After patch:
  - `utils_tests` (full module): `Ran 728 tests — OK (skipped=21)`.
  - `admin_scripts` (full module, including `StartProject`/`StartApp`): `Ran 238 tests — OK`.

*AI assistance disclosure: Arena.ai Agent Mode was used to assist with code analysis, drafting the ticket/patch/tests, and running local verification scripts. All behavior and test suites were verified locally and reviewed manually.*"	Cleanup/optimization	new	Utilities	dev	Low		archive hardening permissions		Unreviewed	0	0	0	0	0	0
