Opened 12 minutes ago
#37568 new Cleanup/optimization
Harden django.utils.archive and TemplateCommand extraction (permission mask, pre-validation, special ZIP entries, streaming)
| Reported by: | VCoder101 | Owned by: | |
|---|---|---|---|
| Component: | Utilities | Version: | dev |
| Severity: | Low | Keywords: | archive hardening permissions |
| Cc: | Triage Stage: | Unreviewed | |
| Has patch: | no | Needs documentation: | no |
| Needs tests: | no | Patch needs improvement: | no |
| Easy pickings: | no | UI/UX: | no |
Description
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)
- Special permission bits preserved (
CWE-276/CWE-732):BaseArchive._copy_permissions()(django/utils/archive.py:108-115) callsos.chmod(filename, mode)directly without masking0o777, preservingsetuid(0o4000),setgid(0o2000), andsticky(0o1000) bits on both TAR and ZIP entries (and passingS_IFMTbits through).TemplateCommand.apply_umask()(django/core/management/templates.py:392-396) usesstat.S_IMODE(os.stat(old_path).st_mode)without& 0o777, preservingsetuid/setgid/stickybits when copying from local--templatedirectories.
- Partial writes before
SuspiciousOperation:- Both
TarArchive.extract()andZipArchive.extract()validate each member'starget_filename()inline during the write loop. If an archive containstpl/good.txtfollowed bytpl/../../escape.txt,good.txtis written to disk before extraction aborts.
- Both
- Non-regular ZIP entries extracted silently:
ZipArchive.extract()does not inspectstat.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.
- Unbounded in-memory reads during ZIP extraction and template download:
ZipArchive.extract()callsself._archive.read(name)before validatingtarget_filename(to_path, name), buffering the entire decompressed member in memory even for invalid paths.TemplateCommand.download()(django/core/management/templates.py:328) callstarget.write(source.read())instead of streaming viashutil.copyfileobj().
UnboundLocalErroron broken symlinks inTarArchive.extract():- If
self._archive.extractfile(member)raisesKeyError/AttributeError(e.g. a broken symlink in a tar archive),finally: if extracted:raisesUnboundLocalErrorbecauseextractedis never initialized beforetry:.
- If
### Proposed changes
- Mask permissions with
& 0o777inBaseArchive._copy_permissions()andTemplateCommand.apply_umask(). - Pre-validate all member target paths (and ZIP POSIX file types) before creating any directories or writing files.
- In
ZipArchive.extract(), reject POSIX file types other than0(DOS/no POSIX mode),stat.S_IFREG, andstat.S_IFDIRwithSuspiciousOperation(f"Archive contains special file: '{orig_name}'"). - Stream
ZipArchive.extract()usingself._archive.open(info)+shutil.copyfileobj(), and streamTemplateCommand.download()usingshutil.copyfileobj(source, target). Call_copy_permissions()after closing the output file. - Initialize
extracted = Nonebeforetry:inTarArchive.extract().
### Relationship to open tickets
- #37390 (PR #22116): filters non-
(isfile|issym|islnk)members inTarArchive. Not modified here (if PR #22116 merges first, rebasing theTarArchive.extract()loop is trivial). - #36588 (PR #21843): adds a
--size-limitcap. Not modified here; streamingZipArchive.extract()anddownload()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, includingStartProject/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.*