Skip to content

B202: detect tarfile extractall imported via a from-import#1442

Open
arpitjain099 wants to merge 2 commits into
PyCQA:mainfrom
arpitjain099:chore/b202-detect-from-import
Open

B202: detect tarfile extractall imported via a from-import#1442
arpitjain099 wants to merge 2 commits into
PyCQA:mainfrom
arpitjain099:chore/b202-detect-from-import

Conversation

@arpitjain099

Copy link
Copy Markdown

Fixes #1171.

B202 (tarfile_unsafe_members) only fired when the file had a bare import tarfile. If you instead write:

from tarfile import TarFile
TarFile(path).extractall(dest)

nothing was reported - a false negative on a genuine path-traversal sink (CWE-22). The cause is the guard: from tarfile import TarFile registers the import as tarfile.TarFile, so is_module_imported_exact("tarfile") is False and the check is skipped.

The fix swaps that for is_module_imported_like("tarfile"), which is how most plugins resolve imports.

I checked it doesn't widen into false positives: extractall with filter="data" stays clean, and an unrelated zipfile.ZipFile(...).extractall() stays clean (the substring "tarfile" isn't in "zipfile.ZipFile"). Added a from-import example and a functional test for it; the full functional suite still passes.

B202 (tarfile_unsafe_members) gated on is_module_imported_exact("tarfile"),
so a from-import like `from tarfile import TarFile` followed by
`TarFile(p).extractall(out)` was not flagged - a false negative on a real
path-traversal sink (the import registers as `tarfile.TarFile`, which the
exact match misses). Switch to is_module_imported_like("tarfile"), matching
how most plugins resolve imports.

Verified it still skips safe cases (filter="data", and unrelated
zipfile.ZipFile().extractall()). Added a from-import example + functional test.

Fixes PyCQA#1171.

Signed-off-by: arpitjain099 <arpitjain099@gmail.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

bandit does not consistently detect extractall with TarFile

1 participant