Search code examples
winapicredentialsadmin-rights

Get restricted user folder when an app requires admin rights and started under admin


There is a Windows app that requires admin rights and this is declared in its manifest. When a restricted user starts it she has to input admin credentials. It's OK and the application works well, but it can't obtain original user folders anymore (ShellAPI returns admin's ones).

Since the application is started under admin initially, there is no point where I can store original user's folder paths to use them later.

Is there a way to get initial restricted user credentials?

Regards,


Solution

  • Because of your manifest, your app is running as an admin user, not the currently logged in restricted user. As David Heffernan mentioned, you should redesign your app to not require the entire app to be run elevated. Delegate your admin tasks to a separate process that runs elevated when needed.

    That being said, if you must run your entire app elevated, all is not lost, but you are going to have to do some extra work.

    1. Start by getting the Session ID that your elevated app is running in. You can do that using WTSQuerySessionInformation() with WTS_CURRENT_SESSION, or ProcessIdToSessionId() with GetCurrentProcessId(), or open the current process's token with OpenProcessToken() and then use GetTokenInformation().

    2. Once you have the Session ID, use EnumProcesses(), GetProcessImageFileName() (or equivalent), OpenProcessToken(), and GetTokenInformation() to find the instance of explorer.exe (or whatever the PC's registered shell app is, which you can find in the Registry) that is running in the same Session ID as your app.

    3. When found, you have the user token for that process from OpenProcessToken(). Duplicate it using DuplicateTokenEx() to get its primary token, and then you can use that token with APIs like LoadUserProfile(), SHGetFolderPath() and SHGetKnownFolderPath() as needed.