Whether Shellexecute will share environment variable with launching process - windows

Program 1 uses SetEnvironment and calls ShellExecute to launch Program 2. Program 2 calls GetEnvironment and retrieves value from it. Surprisingly this is working as i have read in MSDN, SetEnvironment is process specific (at least in my case). Whether ShellExecute internally calls CreateProcess (as child process) which in turn allows Program 2 access ENV variable created and set in Program 1....I use SetEnvironment to create and use a altogether different ENV var than windows user and system vars.

It will share the environment, but not when running elevated (verb="runas").
Then you need to create an intermediate wrapper app (that is elevated) that set environment before re-launching using CreateProcess() or similar.
This is because a non-priviliged user may change the PATH to point to something bad (dir with malicious DLLs) and the elevated app would then be at risk, so one must work around this explicitly.

Related

How to make PowerShell recognize changes in environment variables?

When I change any environment variable in Windows using GUI (System Properties/Environment Variables/System Variables) changes are reflected immediately in cmd terminal, but PowerShell shows an old value.
Here cmd recognized that I changed JAVA_HOME value from C:\Users\nikif\.jdks\openjdk-19.0.1 to C:\Users\nikif\.jdks\corretto-16.0.2
PowerShell still shows the previous value - C:\Users\nikif\.jdks\openjdk-19.0.1
Is there any command that will make PowerShell recognize the environment variable change made in GUI?
Or maybe there is a better way to change the environment variable from PowerShell?
Thank you.
This all should really be a comment (I tried above), but attempting to explain why the question, as it stands, is too vage requires just more explaination.
Processes get their environment when started by the OS. They basically get a copy the environment as it was at that point in time. When you start a process you can (using the respective APIs) pass additional or altered environment variables.
During the existance (runtime) of a process you cannot change the environment.
Shells are a common exception, as they provide specific syntax that does that (set NAME=VALUE in CMD.EXE and $env:NAME="VALUE" in PowerShell, for example). An application itself could also do such stuff from its code using respective APIs. But in general, there is no way to change variables from the outside.
One process will never see the changes done to the environment in a different process. For example, if you have to separate CMD.EXE sessions running and change a variable in one of them, the other will not know. The environment is private to each process.
A potential exception is the (global/system) environment variables you can set using the Computer/Properties/Environment setting (applet). The system will send a WM_SETTINGCHANGE window message indicating the that environment has changed. Applications can register to this message and act accordingly.
However, neither PowerShell nor CMD.EXE do seem to listen to this message (it would require a (hidden) Window anyway and both are console applications). And frankly, it would be not good if they did. Consider CMD.EXE just execuing a batch file and a variable (say PATH) changes underneath - security issues and general havoc all over.

Does "Image File Execution Options" intercept CreateProcess commands?

I want to know how the mechanism of debugger injection works. Why is "Image File Execution Options" so special?
I have two guesses.
CreateProcess will call an internal function that checks against the list of registry keys. If it is found, then it manipulates the arguments and calls the debugger exe instead.
There is some other service listening for CreateProcess calls and intercepts them. It kills the original call or message (if createprocess is a message or message-like), then it runs the new process as if the original caller called it.
My desire is to verify and update components before an application starts. I like the IFEO "feature" but i need to run the original process after the verification step so I need a way to run it without recursing into the updater. I hope that by learning more about the injection system I can get this system working.
This article explains how it works.
In Windows XP and 2003 the user-mode CreateProcess code reads the registry and, if required, launches the debugger instead.
In more recent versions of Windows this functionality has moved into kernel mode.
But neither case seems to involve a general interception mechanism for CreateProcess.

Can one detect how .exe was launched?

I want to be able to detect whether a given exe was shellex'd programmatically or if it was entered and executed interactively in, say, CMD.EXE.
Is there anything about the way an exe is launched that indicates the mechanism that was used to launch it?
Context: Windows XP, Visual Studio 6 languages.
There might be an easier way, but the only way I can think of is to check the parent process name, which involves a few steps:
Get the ID of the parent process.
Get the handle of the process, using the ID.
Use GetModuleFileNameEx with the handle found (and NULL as the module) to get the executable's name.
Check if the executable's name is cmd.exe or whatever.
Bear in mind that the parent process might already be gone when (or while) you do this check.
Edit:
If your program is a console application, you can also check the console it's running in. If it was run from cmd, it will usually use the same console. So, you can use GetConsoleTitle, for instance, and see if it's "Command Prompt". This might not work on localized or different versions of Windows, but it's easy if you have limitated cases. You can also use GetConsoleWindow and GetWindowThreadProcessId instead of steps 1 and 2.
You can differ between say CMD and Explorer by inspecting the parent process, but you can't tell if it happened due to user action or not. Also AFAIK all ways to launch a process result in the same NtCreateProcess/PspCreateProcess call, so you can't tell which API was used either.

What are the differences between "Run as administrator" and a manifest with requireAdministrator?

I've written a program with a manifest that includes requireAdministrator. On Windows 7 systems with UAC enabled, Windows pops up a dialog asking for permissions, as it should. Works great.
If a user starts my program by right-clicking it and choosing "Run as administrator", then Windows 7 also pops up a dialog asking for permissions. However, there are some slight differences in how my program operates in some of the more esoteric parts of my program.
So what are the differences between "Run as administrator" and a manifest with requireAdministrator? Any links to documentation that describe differences would be appreciated.
Edit: This is with UAC enabled.
Edit: As promised below is the full explanation of the difference I'm seeing.
I'm using the EasyHook library to inject a DLL into another process. When my application is run with "Run as administrator", the injected process crashes and EasyHook returns the error "Unknown error in injected assembler code". None of the code in my DLL gets a chance to execute; the crash occurs before then. (Moreover, the crash occurs even if I strip the DLL down to nothing)
If I run my program normally (i.e., elevated via requireAdministrator), everything works fine.
My application is composed of a few different executables. The process that the user launches is not the same process that performs the injection.
With the information given there would be no differences in the permissions between the two processes.
If you request an execution level of "requireAdministrator" via the applications manifest your application will either be launched with the full access token of an administrator or not at all if the user denies consent (see Create and Embed an Application Manifest (UAC) for further information).
The same will happen when a user chooses Run as Administrator.
The only difference is the way that the process is started. When you start an executable from the shell, e.g. by double-clicking in Explorer or by selecting Run as Administrator from the context menu, the shell will call ShellExecute to actually start process execution. The whole process of elevation is hidden inside this function. Kenny Kerr describes this process in more details in Windows Vista for Developers – Part 4 – User Account Control:
ShellExecute first calls CreateProcess to attempt to create the new process. CreateProcess does all the work of checking application compatibility settings, application manifests, runtime loaders, etc. If it determines that the application requires elevation but the calling process is not elevated then CreateProcess fails with ERROR_ELEVATION_REQUIRED. ShellExecute then calls the Application Information service to handle the elevation prompt and creation of the elevated process since the calling process obviously doesn’t have the necessary permissions to perform such a task. The Application Information service ultimately calls CreateProcessAsUser with an unrestricted administrator token.
If on the other hand you want to create an elevated process regardless of what application information is available then you can specify the little-known “runas” verb with ShellExecute. This has the effect of requesting elevation regardless of what an application’s manifest and compatibility information might prescribe. The runas verb is not actually new to Windows Vista. It was available on Windows XP and Windows 2003 and was often used to create a restricted token directly from the shell. This behavior has however changed. Here is a simple example:
::ShellExecute(0, // owner window
L"runas",
L"C:\\Windows\\Notepad.exe",
0, // params
0, // directory
SW_SHOWNORMAL);
So essentially starting an executable using the Run as Administrator option means that ShellExecute bypasses the checks for compatibility settings, application manifests etc and directly requests elevation.
Kenny Kerr's article also has sample code to query the current process' token for its permission using the OpenProcessToken function. Possibly you can use the example to identify that there are no differences in the way your process is elevated.
I'm definitely curious to know which differences you are observing as I strongly doubt they are related to elevation.
As a last thing: Can you double check that you really request a level of requireAdministrator and not by mistake only a level of highestAvailable?
One possible difference might be the rarely used/understood/deliberately-chosen uiAccess attribute. Can you create two manifests, one with uiAccess=false and one with uiAccess=true, then tell us whether one of them gives the same behaviour as you see with right-click-run-as-admin?
The EasyHook documentation for the RemoteHooking class' IsAdministrator property mentions:
Due to UAC on Windows Vista, this property in general will be false even if the user is in the builtin-admin group. As you can't hook without administrator privileges you should just set the UAC level of your application to requireAdministrator.
It's hard to imagine why this is happening, but it is conceivable (especially as you are seeing it happen!) that assets, processes, assemblies, &c, with possibly different trust levels and so forth, will not inherit the elevation of your main app. Setting the requireAdministrator flag may handle/enforce this globally across the entire scope of resources and dependencies. Would love to know how this turns out.
I thought I was seeing a difference between these as well. However, it turned out that in my case the issue was this:
When I click "Run as Administrator" from my file browser (Q-Dir), the working directory is different than when I try simply double clicking an application with requireAdministrator set in the manifest. This changed the behavior of some buggy DLLs I had received. In fact, it turned out that 100% of the differences I saw were due to running from different working directories (specifically, it mattered whether I was on C: drive or a different drive letter) and that the method of getting the program to run as administrator had nothing to do with it.
It's an issue that is specific to my computer's exact configuration, but it is a possible clue into the type of thing that might be happening (or might have happened 7 years ago . . . )

chdir programmatically

In Windows -- and probably Unix for that matter -- using the chdir() function in a (32-bit) program doesn't change the directory when the program exits. (It does in a 16-bit Windows program.)
Does anybody know how to do that in a Windows 32-bit program?
Uhm... IMHO it's exactly one of the things that the OS must guarantee not to happen. The current dir is a per-process property, a child process usually inherits it from the parent process, but the reverse should not happen (and it doesn't).
To obtain what you want, the parent could actively watch some information (message, file, shared memory...) in which the child process stores the new directory, and then call chdir() with the new value.
As far as I know, Windows' cmd.exe doesn't have any mechanism like that.
Actually, by using code injection techniques (e.g. CreateRemoteThread) on the parent process it could be possible to force it to do something unexpected, but it's a very dirty trick, not at all good neither general.
Win16 was different: there was a single "msdos" state for all the programs, but it was a limitation, not a feature.
It sounds like you're asking one process (your Win32 program) to change the CWD of another process (your shell). As far as I know, this is impossible without the latter process providing an API for such a purpose. The nearest I can come to any sort of reference for this assertion, however, is the following quote from MSDN:
A parent process can directly alter the environment variables of a child process during process creation. This is the only situation when a process can directly change the environment settings of another process.
Well yeah it's true the popular API calls to change directory change it for the process. ... BUT ...
(1.) 16-bit windows programs can change the global directory; probably because they run in the same process as the command.com thing. That's what I've been happily using for years; I assume XP somehow emulates this? ... But now Windows 7 64-bit won't run 16-bit programs anymore! (?)
(2.) Both Windows and Unix "cd" commands can of course change directories for the calling process -- presumably because they are built-in commands of the command shell. But successor Windows shells manage to accomplish this, or at least I hope PowerShell can do that. All built-ins?
(3.) The way I've wound-up doing it is modifying my programs that used to call the API to simply emit "cd \dst\directory" to stdout, then in a procedure do
chdirprogram >t~.bat
call T~.bat
Which works great. And of course the usual point of a change-directory program is to provide the functionality in a batch procedure with a computed destination. Which of course you can do in Unix with Bash etc. variables, but not in Windows batch files, although maybe (?) in the numerous successor Windows procedure things, which I don't want to use. ... Since this functionality is obviously useful, I was hoping someone knew of a sneaky Windows call what'd do it. The explanation that it's somehow wrong for a process to change the directory for a calling process is one of those bogus, "you're not supposed to do that and I won't tell you why" excuses. ... But I guess I'll just stick to my pitiful little batch files.
Are you talking about the SetCurrentDirectory function of Windows API? The article says that the function "changes the current directory for the current process". In for instance Delphi, there is a function ChDir that actually calls this API function.

Resources