Skip to content

Safer tempfiles #1450

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
Closed
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
2 changes: 1 addition & 1 deletion git/index/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -351,7 +351,7 @@ def from_tree(cls, repo: "Repo", *treeish: Treeish, **kwargs: Any) -> "IndexFile

# tmp file created in git home directory to be sure renaming
# works - /tmp/ dirs could be on another device
tmp_index = tempfile.mktemp("", "", repo.git_dir)
tmp_index = tempfile.NamedTemporaryFile(dir=repo.git_dir, delete=True).name
arg_list.append("--index-output=%s" % tmp_index)
arg_list.extend(treeish)

Expand Down
3 changes: 2 additions & 1 deletion git/index/util.py
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,8 @@ class TemporaryFileSwap(object):

def __init__(self, file_path: PathLike) -> None:
self.file_path = file_path
self.tmp_file_path = str(self.file_path) + tempfile.mktemp("", "", "")
self.tmp_file_path = str(self.file_path) + osp.basename(tempfile.mkstemp("", "", "")[1])
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The user is responsible for closing the file in [0] or else it will definitely be leaked.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hi @Byron, to be exact, functions that create temporary file names (such as tempfile.mktemp and os.tempnam) are fundamentally insecure, as they do not ensure exclusive access to a file with the temporary name they return. The file name returned by these functions is guaranteed to be unique on creation but the file must be opened in a separate operation. There is no guarantee that the creation and open operations will happen atomically. This provides an opportunity for an attacker to interfere with the file before it is opened.

Also, if nothing else, mktemp has been deprecated since Python 2.3 [ Source ]


# it may be that the source does not exist
try:
os.rename(self.file_path, self.tmp_file_path)
Expand Down