How to secure a temporary folder in Windows

I need to get a safe temp folder where I can store temporary files for my application, but so far my research has led me to conclude that all the approaches that I found are wrong.

The first idea was to use the GetTempPath function, but this causes two problems:

  • The folder may not exist, so I will have to crop the folders one by one to the root and recreate them if they do not exist back to the full path (error prone, tedious)
  • From the "Larry Osterman WebLog" click , it seems that GetTempPath can fall back to USERPROFILE or the Windows directory and extract a whole series of files right there, which is SUPER BAD (TM)!

In the same post there is a suggestion to use GetEnvironmentVariable, but this seems to me a dangerous function (for example, there are no TMP and TEMP envvars).

Is there a cleaning function that I could use? It seems that SHGetKnownFolderPath does not know what the temporary folder is.

+4
source share
4 answers

Your program is probably not the only one that relies on GetTempPath , so it is reasonable to expect that it will return the correct path for writing. Especially since Windows automatically initializes the TMP and TEMP environment variables for you; someone would have to solve some problems in order to undo them, and it would be their responsibility to make sure that the changes did not spoil their system.

I would go on and suggest that GetTempPath working correctly and is worried about crashes when trying to create a temporary file - at this time there may be other errors that you need to check in any case.

+3
source

The idea would be to get the path in which your application ( GetModuleFileNameEx combined with GetModuleHandle(NULL) and GetCurrentProcess ), since this directory cannot be deleted under windows while your application is running from it (maybe m wrong .. . a few years ago I could not do this :)) and create a temporary directory in this directory.

0
source

Your first bullet point is the decision. Wrap it with a method so that you don’t duplicate the code.

0
source

According to this answer , you can use the Boost Filesystem library for this.

0
source

Source: https://habr.com/ru/post/1346558/


All Articles