The run-time hooks that relocate the package's configuration/cache
directory into isolated temporary directory create this directory using
the `tempfile.mkdtemp` function. According to its documentation, the
function creates the temporary directory "in the most secure manner
possible", and the created directory should be "readable, writable, and
searchable only by the creating user ID".
However, this does not apply to Windows, where the 0o700 POSIX
permissions mask passed to the underyling `os.mkdir` call has no effect.
Consequently, the access to the created temporary directory is in fact
gated only by the access to the parent directory. So as long as `TEMP`
and `TMP` point to `%LOCALAPPDATA%\Temp`, the created temporary
directories are typically inaccessible to other users, who do not have
access to the user's home directory. On the other hand, if the temporary
directory base is relocated to a system-wide location (e.g., `c:\temp`),
the temporary directories created by the run-time hooks might become
accessible to other users as well. A malicious user with local access
might thus modify the contents of the temporary directory, interfering
with the application. If the application is running in privileged mode
and developer mode is enabled on the system, they might also attempt
a symlink attack due to lack of hardened mode for `shutil.rmtree`
(used for clean up) on Windows.
Therefore, we replace the use of `tempfile.mkdtemp` with custom function
that uses original `mkdtemp` on POSIX and provides a Windows-specific
implementation that secures the access to created directory via security
descriptor passed to the `CreateDirectoryW` call. This is a
`ctypes`-based port of the code that we already have in bootloader for
mitigating the same issue with temporary directory in onefile builds.
In order to share the implementation among the two run-time hooks that
require it, the code is provided by a new `_pyi_rth_utils` PyInstaller
"fake" package, which is bundled with the frozen application on demand
(i.e., if it is referenced in any of collected run-time hooks).