NuGet: More Than You Bargained to Restore
TL;DR: This NuGet supply-chain security overview explores how restoring or inspecting a .NET project can run attacker-controlled code before you ever launch the application. Securing NuGet means controlling which packages you receive, who can publish them, and what your tools let them do.
Before we hit restore
You have a .NET project in front of you, and you want to take a look. Nothing too adventurous: download the dependencies, check what’s in there, maybe open it in your editor. Running the application can wait. Surely that gives you a chance to figure out whether you trust it first?
That’s where our story starts. We’ll first look at what happens when the project itself is hostile. Restore and inspection can run project-defined build logic, and a project-supplied SDK can turn even dotnet --help into RCE. We’ll also see how a resource file can LFI into a build artifact.
Then we’ll change one thing: the project is yours, but one of its dependencies has gone bad. We’ll follow that package into build hooks, analyzers, and source generators, including the background work your editor does for you, all resulting in RCE. Along the way, we’ll separate ordinary package restore from the import patterns that let dependency code run during restore itself.
Of course, the malicious package still has to get onto your machine. Next, we’ll work backward through that journey: a convincing name, a public package standing in for an internal one, or a new version selected during restore. We’ll look at NuGet’s prefix reservation process, which starts with an email application, and why this badge doesn’t establish much trust. That brings us to source mapping, signatures, and lock files—and what each actually guarantees. Then comes the harder case: what if the attacker can publish under the name you already trust?
We’ll finish with the practical side: protecting publishing credentials, checking packages before they land, keeping untrusted CI work away from secrets, and responding when a malicious release is already out there. The thread through all of it is simple: when we ask NuGet for a package, whose code are we letting run, and at what point did we give it that trust?
- A hostile project can execute code even on
dotnet --helpinto the directory. - Even in your own trusted project, a compromised dependency can execute code while your editor analyzes it.
- NuGet’s prefix reservation starts with an email application, and its badge isn’t proof of publisher identity.

When the attacker controls the project
Someone sends you a .NET project as part of a job interview. It looks like a small coding exercise, and the sender controls every file in the directory. This is the starting point of a Contagious Interview-style attack. A compromised repository or a CI job checking out an untrusted contribution creates the same situation: tools in your environment are about to process attacker-controlled files.
Running the application gives the attacker an obvious opportunity to execute code. Building it also gives them access to your machine: .NET projects can define commands that run during the build, independently of the application itself.
But what if you only want to download its dependencies or check which packages it uses?
Restoring the project
dotnet restore processes the project through MSBuild, .NET’s build engine. MSBuild loads project definitions and imported build files before it can determine what to restore. Those files can also define targets, which group tasks to run at particular stages.
Standard SDK-style .NET projects automatically search the project directory and its parent directories for a file named Directory.Build.targets, importing the nearest one. This file defines shared build instructions. An attacker can add one containing a target that runs before restore:
<Project>
<Target Name="BeforeRestore" BeforeTargets="Restore">
<Exec Command="echo A project task ran before restore" />
</Target>
</Project>
When dotnet restore schedules the Restore target, the imported hook executes.
Inspecting dependencies
Tools that inspect a project often ask MSBuild to describe it. That means a dependency check can reach the same build logic as restore.
For example, dotnet outdated generates dependency information through MSBuild targets. Even this command retains a graph-generation stage that can include restore:
dotnet outdated --no-restore
With this flag, the tool still performs that initial stage. A hostile project can execute its targets while the tool collects information, before the dependency report is ready.
Other tools reach project execution for similar reasons. CycloneDX can invoke restore while generating an SBOM, and NuGetizer invokes targets to inspect package contents. Paket can run explicit build commands configured for Git dependencies.
Asking which SDK is installed
So far, the tools have consumed a project. There is an earlier opportunity: the working directory can influence which SDK implements a dotnet command.
Starting with .NET 10, global.json supports sdk.paths. A project can use it to select an SDK from a local directory:
{
"sdk": {
"version": "10.0.403",
"rollForward": "disable",
"paths": ["repo-sdk"]
}
}
For this attack, the supplied directory must contain a usable SDK/runtime layout, including the SDK entry point and its required configuration and runtime files. A downloaded project archive can carry that layout alongside the source.
With those files in place, even these commands execute the supplied SDK:
dotnet --help
dotnet --version
dotnet --info
This still works when the installed dotnet.exe is invoked by its trusted absolute path. The host selects the local SDK before dispatching the requested command. Some options such as --list-runtimes and --list-sdks follow a separate path and will not select the local SDK.
Reading files into build artifacts
SDK-style projects include **/*.resx by default, including files in subdirectories. An attacker-controlled resource file can use ResXFileRef to embed a local readable file in the resulting DLL:
<data name="leak" type="System.Resources.ResXFileRef, System.Windows.Forms">
<value>C:\ci\private\secret.txt;System.String, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089;utf-8</value>
</data>
The resource build step reads the referenced file and embeds its contents in the DLL. Publishing that DLL or making it available as a CI artifact can then disclose the file to anyone with access to the output.
When the attacker controls only a dependency
Now suppose the project and its configuration are trusted, while the attacker controls a release of a package it already uses.
For a runtime library, the most familiar execution path is an application calling its code. NuGet packages also have several ways to participate in the tools that process the project.
Packages can extend the build tools
During compilation, the build tools can execute code supplied by a dependency. A NuGet package can contain both a library for the application and instructions for MSBuild, for example to generate files or copy native libraries during a build.
Suppose a project already references a compromised version of Boostsecurity.Example. The package can include a file named build/Boostsecurity.Example.targets:
<Project>
<Target Name="PackageBuildHook" BeforeTargets="CoreCompile">
<Exec Command="echo A dependency task ran during compilation" />
</Target>
</Project>
During restore, NuGet extracts the package and generates an import for its .targets file in obj/<project>.csproj.nuget.g.targets. On the subsequent build, MSBuild loads the generated import and runs the hook before CoreCompile. The hook executes the Exec task.
A package can also supply code that the C# compiler runs directly:
- A source generator writes additional C# source during compilation. For example, it might generate the code that converts an application’s objects to JSON. The compiler must load and execute the generator to obtain that source.
- An analyzer examines source code and reports warnings or errors, such as a potentially unsafe use of a null value. The compiler or a supported IDE loads and executes the analyzer to perform those checks.
Packages distribute these extensions as DLLs, commonly under analyzers/dotnet/cs/. When the project includes those assets, the build passes them to the compiler. A malicious extension can execute its payload when the compiler invokes it.
For a trusted project that only needs its dependencies as libraries, a shared configuration can block these execution paths. Place these MSBuild import switches in a trusted Directory.Build.props to prevent loading the generated project-extension files, including NuGet’s package build imports:
<Project>
<PropertyGroup>
<ImportProjectExtensionProps>false</ImportProjectExtensionProps>
<ImportProjectExtensionTargets>false</ImportProjectExtensionTargets>
</PropertyGroup>
</Project>
The SDK can still resolve compiler extensions from the restored package assets. Remove those inputs before compilation through a trusted Directory.Build.targets:
<Project>
<Target Name="RemoveCompilerExtensions" BeforeTargets="CoreCompile">
<ItemGroup>
<Analyzer Remove="@(Analyzer)" />
</ItemGroup>
</Target>
</Project>
This policy leaves ordinary library references available, but also removes trusted compiler extensions and disables other generated project-extension imports. Packages that depend on build instructions or generated source may no longer build. When some dependencies need extensions that you trust, NuGet’s separate asset categories allow a finer selection instead of coarse suppression. A project that only needs a particular package’s library can request exclusions on that PackageReference:
<PackageReference Include="Boostsecurity.Example" Version="1.2.*"
ExcludeAssets="build;buildMultitargeting;buildTransitive;analyzers" />
This keeps the package’s compile and runtime assets while requesting exclusion of its build imports and compiler extensions. PrivateAssets="all" serves a different purpose: it only controls which assets flow to consuming projects. The current project can still use them.
Inspection can invoke those same extensions
These execution paths are not limited to an explicit build. Tools that inspect a project need to identify its source files, resolve references, and obtain compiler options. Those answers can depend on the same package-supplied targets and compiler extensions.
After it accepts and opens a project, Visual Studio obtains this information through background design-time builds. These run selected MSBuild targets without producing the application’s normal compiled output. A malicious package can attach a hook to reference resolution instead of an ordinary compilation stage:
<Project>
<Target Name="PackageInspectionHook" BeforeTargets="ResolveAssemblyReferences">
<Exec Command="echo A dependency task ran during project inspection" />
</Target>
</Project>
Once restore has prepared the package’s build import, a design-time build that reaches ResolveAssemblyReferences also runs this hook.
Compiler extensions provide another path. Editor analysis executes applicable analyzers to obtain diagnostics and can run source generators to obtain generated code. A formatting check can require similar processing:
dotnet format --verify-no-changes --no-restore
Neither flag disables executable package extensions already available from a previous restore, as warned by Microsoft’s dotnet format documentation.
Does restoring the dependency execute it?
For an ordinary library referenced through PackageReference, restore does not execute the dependency’s code. Restore downloads and extracts the package, resolves dependencies, and prepares imports for later builds. Normal package build imports become active in later project operations, and analyzers and source generators run through compiler or IDE integration. Legacy install scripts are outside the PackageReference restore lifecycle.
The answer changes if the trusted project explicitly imports a build file from a dependency:
<Import Project="$(NuGetPackageRoot)boostsecurity.example/1.2.3/build/Boostsecurity.Example.targets" />
If the package file is already available at that path when MSBuild evaluates the project for restore, the explicit import loads it. A malicious release can contain a target with BeforeTargets="Restore". When MSBuild schedules Restore, the hook runs. Explicitly importing package-provided build files is a pattern used in projects such as Microsoft’s WinUI repository.
A NuGet-distributed MSBuild SDK is another executable dependency. For example, dotnet/runtime imports Microsoft.DotNet.Arcade.Sdk, with its package version selected in global.json:
<Import Project="Sdk.props" Sdk="Microsoft.DotNet.Arcade.Sdk" />
MSBuild resolves the SDK package and loads its build definitions during project evaluation, including on the first restore. A malicious selected SDK release can therefore supply restore hooks.
How does the malicious package reach you?
We now know what a malicious dependency can do. The next question is how it becomes your dependency.
Source and build compromise are possible in NuGet, just as in other ecosystems. We covered those routes in our articles on SLSA source security and build security.
Source: SLSA v1.2 supply-chain threats. The model includes artifact publication (F), distribution (G), and package selection (H), alongside source and build threats.
NuGet’s naming rules, source selection behavior, and registry policies create additional registry-level attack paths.
Getting a lookalike package selected
An attacker can register a name close to a popular package and wait for a typing mistake, an attack known as typosquatting. NuGet names also offer an opportunity to impersonate an organization’s package family. In Boostsecurity.Example, the dot is an ordinary character in the package ID. Even after a Boostsecurity organization is created, unrelated publishers can register available Boostsecurity.* IDs.
nuget.org offers package ID prefix reservation through an email application and review process. A restricted reservation for Boostsecurity. limits new matching IDs to authorized owners. Qualifying packages display a badge indicating that an owner has a matching reserved prefix, without identifying the owner or the prefix.
Existing packages owned by someone else retain their IDs and can receive new versions after a matching prefix has been reserved. Owners can also request a public prefix, which permits unrelated publishers to create matching IDs while qualifying owners receive the badge.
Prefix reservation is therefore a limited ownership signal, not proof that every package with a matching name belongs to the expected publisher. By contrast, npm scopes and domain-based naming in Go and Maven provide a stronger basis for identifying the expected publisher from the package name. In NuGet, use the package’s specific owners, rather than its package ID, to establish publisher identity.
Getting a public package selected instead of an internal one
Dependency confusion occurs when a consumer intended to use an internal package instead selects an attacker’s package with the same ID from another source.
Suppose a project references Boostsecurity.Example and can restore from both a private feed and nuget.org. An outside publisher who can register that ID on the public feed may get an opportunity to supply it.
Package Source Mapping lets the consumer restrict which sources are eligible for each package ID. For example:
<configuration>
<packageSources>
<clear />
<add key="internal" value="https://packages.boostsecurity.example/v3/index.json" />
<add key="public" value="https://api.nuget.org/v3/index.json" />
</packageSources>
<packageSourceMapping>
<packageSource key="internal">
<package pattern="Boostsecurity.*" />
</packageSource>
<packageSource key="public">
<package pattern="*" />
</packageSource>
</packageSourceMapping>
</configuration>
With a supported client using this configuration, Boostsecurity.* takes precedence over the broader * pattern. When NuGet needs to download Boostsecurity.Example, it asks the internal source. If that feed lacks the package, restore fails. The mapping needs to cover the entire dependency graph, including transitive dependencies.
If the private feed proxies nuget.org, it can still serve a public substitute through the mapped internal endpoint. Configure the feed to block public upstream resolution for internal names across every endpoint consumers use. Feeds such as Azure Artifacts can also restrict who imports new upstream releases.
Checking who signed the package
If a public substitute for Boostsecurity.Example reaches the client, a signer policy provides another check. NuGet distinguishes:
- Author signatures: the publisher signs with a certificate whose fingerprint the consumer can approve.
- Repository signatures: the registry signs the package, attesting that it accepted those contents.
A consumer can configure approved certificates in trustedSigners in NuGet.Config and set signatureValidationMode to require, on clients with signature verification enabled and supported. NuGet accepts a package that satisfies any trusted-signer entry.
Trusting a public repository’s signing certificate without owner restrictions authenticates the repository but does not distinguish trusted publishers from arbitrary uploaders. For publisher-level control, trust selected author certificates or restrict repository trust to approved package owners. Trusting a private repository signature is useful if its package admission controls are trustworthy.
Why lock files are important
A NuGet lock file, packages.lock.json, records the resolved dependency graph, including transitive dependencies and package content hashes. Reviewing and committing it, then enforcing it with dotnet restore --locked-mode, preserves those selections.
nuget.org and Azure Artifacts reject replacement of already-published package contents under the same ID and version, giving an immutability guarantee. This immutability might appear to make a lock file unnecessary: an attacker cannot overwrite an existing legitimate release. However, immutable releases do not guarantee stable dependency resolution.
Dependency resolution can change the selection in two ways:
Version="1.2.3"specifies a minimum version. If that version is unavailable, NuGet can select the lowest applicable higher version and report NU1603. A future publication of1.2.3would result in a change in package resolution. Use an exact constraint such asVersion="[1.2.3]"to require the intended release.- A floating reference such as
Version="1.2.*"selects the highest matching stable version. A fresh resolution without an enforced lock can therefore adopt a newly published malicious release.
Other feeds may permit same-version replacement through configured permissions or deployment policies, including Artifactory and Nexus. Some implementations also permit deletion followed by republication. NuGet’s feed contract explicitly allows replacement rather than requiring immutability.
The lock file covers a particular dependency graph. Other acquisition paths are not all covered. For example, MSBuild supports PackageDownload, a project item for downloading exact package versions, but those downloads are not covered by packages.lock.json.
Publishing under the expected package identity
Name and source checks help reject competing packages. An attacker with publication authority can instead upload a malicious release under the expected name. A compromised maintainer account, compromised CI workflow, or leaked NuGet API key can provide that authority.
nuget.org requires two-factor authentication, but the kind of second factor matters. FIDO2 security keys and passkeys bind authentication to the service’s domain, making them phishing-resistant choices for accounts that control publication. API keys remain a separate publishing credential that needs its own scope, expiration, and storage controls.
Who else must approve the release?
Suppose the team requires a second maintainer to review source-code changes before they reach the default branch, as required by SLSA Source L4. That branch should be the source for published releases. If one maintainer’s account is compromised, the team expects the second person to stop an unauthorized release.
On nuget.org, each authorized package owner can publish independently, and organization collaborators and administrators also have publishing rights. An authorized individual can also change their trusted-publishing policy on their own, and ownership changes can proceed without every existing owner’s agreement.
This is not unique to nuget.org, but requiring another person’s approval for publishing-policy and ownership changes would help preserve that boundary at the registry.
Protecting publishing credentials
NuGet trusted publishing lets a CI workflow exchange an OpenID Connect (OIDC) token for a short-lived NuGet API key. nuget.org checks the token against a policy identifying the approved repository and workflow. A compromised approved workflow can still request a key, so protect its definition, dependencies, and execution environment as part of the release process.
This is a better alternative to long-lived API keys. It also helps reduce the supply-chain attack surface by linking source, build, and distribution.
Detection and prevention
A release that passed yesterday’s checks may be identified as malicious or vulnerable today. NuGet Audit reports known advisories. For PackageReference projects, explicitly selecting NuGetAuditMode=all includes transitive dependencies.
Boost Security’s Dazio scans NuGet packages for known malware and can check downloads through the user’s NuGet.Config. With install protection enabled in block mode, it blocks downloads identified as malicious. It can also help detect weaknesses in project configuration.
A minimum package age requirement provides another way to reduce exposure to newly published packages. .NET 11 RC2, released in October 2026, supports this feature.
Handling untrusted contributions in CI
CI routinely builds untrusted contributions. Treat restore, inspection, and build steps as opportunities for that contribution to execute code. Use a disposable, low-privilege environment with isolated caches and no release credentials, signing keys, secrets, or OIDC publishing authority.
As a defense-in-depth measure, a trusted project can build untrusted contributions while limiting exposure to the threats described in this article. Place the contribution in a fixed subdirectory beneath a protected parent containing the trusted project:
.
├── App.csproj
├── global.json
├── NuGet.Config
├── packages.lock.json
└── untrusted/
Run commands from the trusted parent, explicitly target App.csproj, and select NuGet.Config with restore’s --configfile option. Keep the parent’s sdk.paths entries within trusted locations. In this layout, SDK selection and automatic directory-build discovery begin in the trusted parent. Keep that directory, its ancestors, and its obj/ outside the contributor’s write access, since MSBuild can automatically import files such as obj/App.csproj.evil.targets during a build.
Commit the trusted project’s reviewed packages.lock.json and enforce it with --locked-mode during restore.
dotnet restore App.csproj --configfile NuGet.Config --locked-mode
Exclude child resources in the trusted project if they are not needed:
<ItemGroup>
<EmbeddedResource Remove="untrusted\**\*.resx" />
</ItemGroup>
The trusted project must also control every imported build file and compiler extension, including those supplied by dependencies.
Incident response
Suppose you maintain a package and discover a malicious release under its name. Once you have contained the affected account, credential, or publishing workflow, the existing release still needs attention.
Start by unlisting the affected versions without hiding the package’s other releases. This makes the malicious versions harder to discover, but exact-version restores remain possible, and some floating-version requests can still select an unlisted release. Deprecation adds a warning and can suggest an alternative while leaving the version available for restore. Contact NuGet support about removal, providing the affected versions and evidence through the package’s support route. Maintainers cannot permanently delete releases themselves, but NuGet staff can remove harmful packages.
Notify users and security tools by publishing a security advisory, such as a GitHub Security Advisory (GHSA). Include the affected package IDs and versions, known malicious behavior, and a safe replacement, if available.
Conclusion
Supply-chain security asks whether software came from the expected producer, whether it was altered along the way, and whether we should trust it. Answering these questions means protecting the whole journey: developer workstations, source repositories, automated pipelines, dependencies, and distribution. It also means looking beyond the final application. Other libraries, runtime images, workstation tools, CI systems, and deployed infrastructure all consume software and inherit its risks.
NuGet offers useful pieces of that puzzle: lock files, source mapping, and author signatures. But the trust we grant a project and its dependencies goes further than many of us expect. Simply restoring or inspecting a project can give an attacker a way in, before we think we have agreed to run anything. A compromised dependency offers further entry points. As we explored in our Go research, ecosystem design can close off many of these paths by default, without making trust automatic. The goal is not just to download the right package, but to know whose code we are trusting, where, and to do what.