Skip to content

Fix ProcessStartInfo environment for alternate Windows users - #137445

Open
adamsitnik wants to merge 7 commits into
dotnet:mainfrom
adamsitnik:fix-136746-logon-env
Open

adamsitnik wants to merge 7 commits into
dotnet:mainfrom
adamsitnik:fix-136746-logon-env

Conversation

@adamsitnik

Copy link
Copy Markdown
Member

Summary

  • On Windows, initialize ProcessStartInfo.Environment from the specified user's environment using LogonUser and CreateEnvironmentBlock, without inheriting the caller's variables. Network-only credentials continue to use the caller's environment.
  • Share the existing Windows environment-block parser between CoreLib and Process. Keep the logon code trimmable when UserName is never set.
  • Reject credential changes that would invalidate an already captured environment snapshot.

Accessing the environment for a specified user now authenticates that user and can throw if the credentials are invalid. The user's profile is not loaded to construct the snapshot, so profile-specific variables may be missing even when LoadUserProfile is set.

Validation

  • dotnet build src\libraries\System.Diagnostics.Process\src\System.Diagnostics.Process.csproj — passed.
  • dotnet build src\libraries\System.Diagnostics.Process\tests\System.Diagnostics.Process.Tests.csproj /t:Test "/p:XUnitOptions=-class System.Diagnostics.Tests.ProcessStartInfoTests" — passed: 75 total, 0 failed, 2 skipped.
  • The administrator-only target-user test was reported passing on an earlier revision; its subsequently added setter-order assertions have not been rerun elevated.
  • NativeAOT trimming was verified on an earlier revision: an app that did not set UserName did not retain the logon helper or Userenv imports. It was not rerun after the parser and ordering changes.
  • A checked CoreLib build targeting clr.corelib+clr.nativecorelib+libs.pretest -rc checked failed during crossgen with 0xC0000005; the cause has not been determined.

Resolves #136746

Note

This PR description was generated with GitHub Copilot.

adamsitnik and others added 4 commits November 12, 2026 17:55
….Environment with UserName set

On Windows, when UserName is set (and UseCredentialsForNetworkingOnly is not),
ProcessStartInfo.Environment is now populated using LogonUser + CreateEnvironmentBlock,
so the child process gets the target user's environment instead of the parent's.

Fixes dotnet#136746

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
Copilot-Session: f1f4be50-afad-498e-96d6-62c7358bd322
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>

Copilot-Session: f1f4be50-afad-498e-96d6-62c7358bd322
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>

Copilot-Session: f1f4be50-afad-498e-96d6-62c7358bd322
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>

Copilot-Session: f1f4be50-afad-498e-96d6-62c7358bd322
@azure-pipelines

Copy link
Copy Markdown
Azure Pipelines:
Successfully started running 3 pipeline(s).
12 pipeline(s) were filtered out due to trigger conditions.
There may be pipelines that require an authorized user to comment /azp run to run.

@dotnet-policy-service

Copy link
Copy Markdown
Contributor

Tagging subscribers to this area: @dotnet/area-system-diagnostics-process
See info in area-owners.md if you want to be subscribed.

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🟡 Changes recommended

The Windows-only parser include leaves Linux/macOS CoreCLR callers without its definition, and the tests do not adequately verify environment isolation for alternate-user and network-only credentials.

2 open issues
What changed in this PR

This PR updates Windows ProcessStartInfo.Environment to use the specified user's environment rather than the caller's, addressing incorrect variables when launching a process under alternate credentials.

Changes:

  • Creates target-user environment snapshots through Windows logon APIs while preserving caller variables for network-only credentials.
  • Shares environment-block parsing with CoreLib and guards credential changes after snapshot capture.
  • Adds Windows tests and documents authentication and profile-loading behavior.
File Description
src/​libraries/​System.Private.CoreLib/​src/​System/​Environment.Variables.Windows.cs Delegates environment parsing to the shared helper.
src/​libraries/​System.Private.CoreLib/​src/​System.Private.CoreLib.Shared.projitems Includes the shared parser in CoreLib.
src/​libraries/​System.Diagnostics.Process/​tests/​ProcessStartInfoTests.Windows.cs Adds credential and environment-snapshot tests.
src/​libraries/​System.Diagnostics.Process/​src/​System/​Diagnostics/​ProcessStartInfo.Windows.cs Creates target-user snapshots and guards credential changes.
src/​libraries/​System.Diagnostics.Process/​src/​System/​Diagnostics/​ProcessStartInfo.cs Selects environment defaults and documents snapshot behavior.
src/​libraries/​System.Diagnostics.Process/​src/​System.Diagnostics.Process.csproj Includes the parser and Windows interop sources.
src/​libraries/​System.Diagnostics.Process/​src/​Resources/​Strings.resx Adds the credential-change error message.
src/​libraries/​Common/​src/​System/​EnvironmentBlockParser.Windows.cs Extracts reusable environment-block parsing.
src/​libraries/​Common/​src/​Interop/​Windows/​Userenv/​Interop.CreateEnvironmentBlock.cs Declares environment-block creation and cleanup APIs.
src/​libraries/​Common/​src/​Interop/​Windows/​Interop.Libraries.cs Adds the Userenv library constant.
src/​libraries/​Common/​src/​Interop/​Windows/​Advapi32/​Interop.LogonUser_SafeTokenHandle.cs Declares logon interop using a safe token handle.

Review effort: Balanced

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🟡 Changes recommended

Regression tests omit coverage of domain and network-only credential mutation guards, and the documentation incorrectly promises the target user's environment for network-only credentials.

1 open issue
1 previously missed issue

In code that hasn't changed since last review

Low severity Qualify target-environment guarantee for network-only credentials

src/​libraries/​System.Diagnostics.Process/​src/​System/​Diagnostics/​ProcessStartInfo.cs:103

This also describes network-only credentials, but GetDefaultEnvironmentVariables deliberately returns the caller's environment in that case. The current wording therefore incorrectly promises the target user's environment—and exclusion of caller-only variables—whenever UserName is set. Qualify this statement with UseCredentialsForNetworkingOnly == false.

2 resolved since last review

Review effort: Balanced

set
{
#if TARGET_WINDOWS
ThrowIfEnvironmentWasAccessed(

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Is this a breaking change?

startInfo.Environment.Add("MYVALUE", "MYVARIABLE");
startInfo.UserName = "MYUSERNAME";

worked before, and it is going to throw exception now.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Is this a breaking change?

It is. Overall I don't think we can fix this bug without introducing a breaking change. I'll add the label.

@jkotas jkotas Nov 13, 2026 •

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Also, the new behavior is non-intuitive - it violates .NET Framework design guidelines: "DO allow properties to be set in any order, even if this results in a temporary invalid state of the object."

I understand what you are trying to do here. The cure may be worse than the disease.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

I don't think we can fix this bug without introducing a breaking change.

It is not clear whether the current behavior - that existed for decades - is a bug. The behavior may be unexpected by some users, but it does not make it a bug.

You can fix the user scenario by introducing a new API, without introducing a breaking change.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

It is not clear whether the current behavior - that existed for decades - is a bug.

In my opinion it's a bug (depending if I use given property, the process is started with different set of env vars which can include secrets from the parent process), but most likely very few people have noticed it.

I know that I can introduce a new API (get env vars for specific user), the problem is that the users would need to be aware of the problem and of the fact that we provide a new API. If we introduce a breaking change that throws, it forces the users to read the docs and act.

golang was initially hesitant to make such a change (golang/go#29534), but they introduced it as well: https://go-review.googlesource.com/c/go/+/176619

@SteveL-MSFT what is your opinion on this matter from PowerShell perspective? (PowerShell/PowerShell#4671)

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

golang was initially hesitant to make such a change (golang/go#29534), but they introduced it as well: https://go-review.googlesource.com/c/go/+/176619

This talks about nil environment (ie default) + user token. I think the .NET API works fine for this case.

The .NET API has the issue only once you customize environment on ProcessInfo. Does golang have a solution for that case?

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

startInfo.Environment.Add("MYVALUE", "MYVARIABLE");
startInfo.UserName = "MYUSERNAME";

worked before, and it is going to throw exception now.

(Original reporter here, hello) IMO "worked" seems like a bit of a misnomer here. The child process ended up in an environment that was effectively completely broken. Any usage of foundational environment information like USERNAME, APPDATA, and even TEMP would yield paths that may be unusable at best, or an unexpected cross-user privilege management failure at worst (depending on whether the parent or child had higher privileges).

Like was mentioned, secrets from the environment of the host process would also end up being unexpectedly propagated into the child environment, which could be considered a vulnerability.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Short answer: Go does not have a dedicated solution for this case either. It gives the user a way to obtain the token user's default environment, modify it, and assign it back. It never merges a custom environment with anything.

Details, based on current Go sources:

  1. Default environment (Cmd.Env == nil): (*Cmd).environ() calls execenv.Default(c.SysProcAttr) (exec.go#L1216). When SysProcAttr.Token is set, it calls CreateEnvironmentBlock(token, inherit: false) and returns the target user's environment (execenv_windows.go#L23-L28). This is the change from https://go-review.googlesource.com/c/go/+/176619.
  2. Custom environment: Cmd.Env is a plain []string that completely replaces the default (exec.go#L162-L164). The common idiom cmd.Env = append(os.Environ(), "K=V") passes the caller's environment to the other user, which is the same problem .NET has today.
  3. What Go offers for that case:
  4. Caveat: if CreateEnvironmentBlock fails, environ() falls back to os.Environ() (exec.go#L1218), and the public Environ() intentionally discards the error (exec.go#L1255). So in Go, a failure silently gives the caller's environment to the other user.

How this maps to this PR: ProcessStartInfo.Environment is the .NET equivalent of Cmd.Environ(). It is lazily populated, and with this PR it is populated from the target user when UserName is set (and UseCredentialsForNetworkingOnly is not), so customizing it in place works as expected. Differences from Go:

  • Go relies on the user setting Token before calling Environ(). We enforce that ordering by throwing InvalidOperationException when UserName, Domain, or UseCredentialsForNetworkingOnly change in a way that would affect the environment after Environment was accessed.
  • Go receives an existing token, while ProcessStartInfo only has user name, domain, and password, so we call LogonUser ourselves to get the token.
  • We throw Win32Exception on failure instead of falling back to the caller's environment.

Note

This comment was generated with the help of GitHub Copilot.

@adamsitnik adamsitnik added breaking-change Issue or PR that represents a breaking API or functional change over a previous release. needs-breaking-change-doc-created Breaking changes need an issue opened with https://github.com/dotnet/docs/issues/new?template=dotnet labels Nov 13, 2026
@dotnet-policy-service

Copy link
Copy Markdown
Contributor

Added needs-breaking-change-doc-created label because this PR has the breaking-change label.

When you commit this breaking change:

  1. Create and link to this PR and the issue a matching issue in the dotnet/docs repo using the breaking change documentation template, then remove this needs-breaking-change-doc-created label.
  2. Ask a committer to mail the .NET Breaking Change Notification DL.

Tagging @dotnet/compat for awareness of the breaking change.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area-System.Diagnostics.Process breaking-change Issue or PR that represents a breaking API or functional change over a previous release. needs-breaking-change-doc-created Breaking changes need an issue opened with https://github.com/dotnet/docs/issues/new?template=dotnet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Setting Environment Variable on Process Started as Other User Uses Wrong Environment

4 participants