Skip to content

FileManager: avoid a TOCTOU issue in computing CWD #1035

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

Merged
merged 1 commit into from
Nov 7, 2024
Merged
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
Original file line number Diff line number Diff line change
Expand Up @@ -466,13 +466,22 @@ extension _FileManagerImpl {

var currentDirectoryPath: String? {
#if os(Windows)
let dwLength: DWORD = GetCurrentDirectoryW(0, nil)
return withUnsafeTemporaryAllocation(of: WCHAR.self, capacity: Int(dwLength)) {
if GetCurrentDirectoryW(dwLength, $0.baseAddress) == dwLength - 1 {
return String(decodingCString: $0.baseAddress!, as: UTF16.self)
var dwLength: DWORD = GetCurrentDirectoryW(0, nil)
guard dwLength > 0 else { return nil }

for _ in 0 ... 8 {
if let szCurrentDirectory = withUnsafeTemporaryAllocation(of: WCHAR.self, capacity: Int(dwLength), {
let dwResult: DWORD = GetCurrentDirectoryW(dwLength, $0.baseAddress)
if dwResult == dwLength - 1 {
return String(decodingCString: $0.baseAddress!, as: UTF16.self)
}
dwLength = dwResult
return nil
}) {
return szCurrentDirectory
}
return nil
}
return nil
#else
withUnsafeTemporaryAllocation(of: CChar.self, capacity: FileManager.MAX_PATH_SIZE) { buffer in
guard getcwd(buffer.baseAddress!, FileManager.MAX_PATH_SIZE) != nil else {
Copy link
Contributor

Choose a reason for hiding this comment

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

One quick question - on non-Windows we just allocate a buffer of MAX_PATH_SIZE (1024 bytes IIRC) and assume that the path will fit (returning nil if for some reason it doesn't). Just confirming - I assume there's no equivalent for Windows that we should use either instead of requesting the buffer size or using in the case of the size check failing?

Copy link
Member Author

Choose a reason for hiding this comment

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

Yeah, there is no real equivalent for Windows. The majority of the API surface on Windows is designed to assume that you will query the required sizes. In the case of the file system, the only place there is a small buffer size guarantee is the Win32 API surface and in Foundation we will bypass that layer entirely when working with paths to ensure that long paths work.

Expand Down