A .NET build that restores from both nuget.org and a private feed, with no source mapping, no lock file and no signature policy, will take whichever package answers first. That is the mechanism behind dependency confusion, and NuGet now ships the controls to close it: Package Source Mapping, packages.lock.json with locked-mode restore, client trust policies for signed packages, NuGetAudit for known vulnerabilities, and on the publishing side scoped API keys, ID prefix reservation and Trusted Publishing with short-lived keys. This guide explains how each works, how they fit together for consumers and publishers, what to log, and the configuration mistakes that leave them ineffective. It is written for .NET platform owners, build engineers and AppSec teams. For application-level .NET hardening, see the .NET Security Guide. Feature details were checked against Microsoft's NuGet documentation on 27 October 2026.
This is an independent guide from NHI Mgmt Group, based on Microsoft's public documentation as of November 2026. It is not sponsored or reviewed by Microsoft. Product features change, so confirm settings against Microsoft's current documentation.
Key takeaways
- Map every package to a source. Once
packageSourceMappingis defined, every package, including transitive ones, must match a pattern; internal prefixes such asContoso.*resolve only from the private feed. - Know the mapping's limits. Source mapping applies to downloads during restore, install and update only; metadata commands such as
dotnet list package --vulnerablestill send package IDs to every configured source, and packages already in the global packages folder skip source lookup. - Lock, then restore in locked mode.
RestorePackagesWithLockFilerecords the full closure with content hashes;dotnet restore --locked-modein CI fails rather than silently changing the graph. - Signatures only help when required. Packages signed with untrusted certificates are treated as unsigned. Set
signatureValidationModetorequirewith explicittrustedSignersto make signing a control. - Retire long-lived publishing keys. Use Trusted Publishing (OIDC exchange for a one-hour key) where your CI supports it, otherwise scoped, expiring API keys per package set; delete legacy all-package keys.
How identity and access work in NuGet
NuGet has two sides with different identity models, and supply chain security needs both.
| Side | Identity | Credential | What it controls |
|---|---|---|---|
| nuget.org publisher | Individual account (Microsoft account or Microsoft Entra ID) or organisation account | Interactive login with mandatory 2FA; API keys or Trusted Publishing for push | Who can push, unlist and manage owners for a package ID |
| Private feed publisher | Feed's own identity system (for example Azure Artifacts, GitHub Packages, Artifactory) | Feed-specific tokens | Internal package publication |
| Consumer (developer or build agent) | Whoever runs restore | packageSourceCredentials or a credential provider for authenticated feeds | Which sources are queried, which packages are accepted |
| Package signer | X.509 code signing certificate holder | Signing key (RSA 2048 bits or more for nuget.org) | Author signature that consumers can pin in trust policy |
nuget.org requires two-factor authentication on every account. Repository signatures are applied by nuget.org to every uploaded package and include owner metadata at the time of submission, which is what lets a consumer trust "packages from nuget.org owned by microsoft" rather than just "packages from nuget.org".
Admin roles and privileged access
Organisation accounts on nuget.org have two member roles. The NuGet documentation lists their permissions as follows.
| Permission | Collaborator | Administrator |
|---|---|---|
| Manage the organisation's packages (submit, update or unlist) | Yes | Yes |
| Change organisation metadata (email, notifications) | No | Yes |
| Manage organisation members | No | Yes |
| Request or act on co-ownership requests | No | Yes |
- Publish through an organisation: own production packages with an organisation account rather than an individual, so leavers can be removed without transferring package ownership.
- Keep administrators few: two or three named administrators, reviewed quarterly. A sole administrator cannot remove themselves until another is added, which is a useful guard against orphaned organisations.
- Reserve your prefix: ID prefix reservation (requested by email to [email protected]) makes nuget.org reject new packages matching the prefix unless they come from the reserving owners, and shows a verified indicator in the gallery and Visual Studio. Existing third-party packages that already match are not removed, and a prefix marked public keeps the indicator but does not block others.
- Watch co-ownership: co-ownership requests are a path to adding an owner to a package. Treat acceptance as a privileged change.
Integrations, API tokens and service accounts
Publishing credentials are the non-human identities of the NuGet supply chain. A stolen push key lets an attacker publish a malicious version under your package ID. See the RubyGems, NuGet and Crates.io Publishing Tokens Guide for the cross-registry view.
| Option | Lifetime | Scope | Use when |
|---|---|---|---|
| Trusted Publishing | Temporary API key valid for one hour; each OIDC token can be exchanged once | Policy bound to repository owner, repository, workflow file and optional environment | Publishing from GitHub Actions or GitLab CI/CD (the documented integrations) |
| Scoped API key | Expiry set at creation (for example 365 days); email warning ten days before expiry | Selected packages or a glob such as fabrikam.service.*, and selected push or unlist scopes | Other CI systems, or until Trusted Publishing is adopted |
| Legacy API key | Never expires; retired only after 365 days without a push | All permissions on all the account's packages | Never. The documentation recommends deleting it. |
- Trusted Publishing setup: add a policy on nuget.org naming the repository owner, repository and workflow file name (not path), and optionally a GitHub environment such as
release; give only the publishing jobid-token: write; request the key immediately beforedotnet nuget push. Bind the policy to a protected environment so only reviewed release runs can publish. - Glob scope caution: a key scoped to
fabrikam.service.*can also push new package IDs matching the glob. Pair globs with prefix reservation. - Refresh versus delete: refreshing issues a new key with the same scope and expiry and invalidates the old one; use it after suspected exposure. Deleted keys cannot be recovered.
- Feed credentials on build agents: NuGet encrypts
passwordvalues inpackageSourceCredentialsonly on Windows, and only for the same user and machine. Elsewhere usecleartextpasswordwith an environment variable reference or a credential provider, never a literal token in a committednuget.config. On Linux, keep anynuget.configreadable only by its owner. - Secret scanning: GitHub secret scanning detects NuGet API keys committed to repositories. Make sure push protection is on for repositories that publish packages. See the Git Secret Scanning Guide.
Logging and detection
NuGet restore is not an audit log, but its warnings and the surrounding systems give useful signals.
| Signal | Source | What it indicates |
|---|---|---|
| NU1901 to NU1904 | NuGetAudit during restore | Package with low, moderate, high or critical advisory |
| NU1900, NU1905 | NuGetAudit | Vulnerability data could not be fetched, or an audit source has no vulnerability database: audit coverage is reduced, so treat these warnings as errors |
| NU3008 | Signature verification | Signed package content modified since signing: block and investigate |
| NU1110 | Source mapping | A package in the global packages folder came from a source not enabled for this solution |
| Locked-mode restore failure | CI | Dependency graph changed without a lock file update |
| New package version, owner change, API key creation | nuget.org account email notifications; private feed audit logs | Unexpected publication or ownership change |
| Outbound requests to public feeds for internal IDs | Proxy or DNS logs | Metadata leakage of internal package names (the documented source mapping gap) |
Treat high and critical advisories as errors with <WarningsAsErrors>$(WarningsAsErrors);NU1903;NU1904</WarningsAsErrors>, which the documentation gives as an option for teams not using TreatWarningsAsErrors. Record every NuGetAuditSuppress entry with an owner and expiry, because a suppression applies to the advisory across the project.
Metrics: percentage of repositories with source mapping and a committed lock file (for applications); percentage of CI restores in locked mode; open high or critical NuGetAudit findings and their age; number of legacy or non-expiring publishing keys (target zero); percentage of package publishes via Trusted Publishing.
Hardening baseline
Consumers: sources and mapping
- One repository-root
nuget.config: beginpackageSourcesandpackageSourceMappingwith<clear />so no user- or machine-level source is inherited, as the NuGet security best practices recommend. - Map internal prefixes: under the private source, add
<package pattern="Contoso.*" />; the most specific pattern wins (exact IDs over prefixes, longer prefixes over shorter,*lowest). - Choose the default deliberately:
*on nuget.org suits teams with consistent internal prefixes;*on a private upstreaming proxy suits teams that vet public packages or lack a naming convention. See the Private Package Repository and Proxy Guide. - Isolate the global packages folder: set
globalPackagesFolderper repository (orNUGET_PACKAGESon agents), because a package already in the cache bypasses source lookup and mapping. - Use current tooling everywhere: source mapping needs NuGet 6.0, .NET SDK 6.0.100 or Visual Studio 2022; older tools ignore it, so a stale build agent quietly loses the protection.
Consumers: integrity and vulnerabilities
- Lock files: set
<RestorePackagesWithLockFile>true</RestorePackagesWithLockFile>, commitpackages.lock.jsonfor applications (the documentation advises against relying on it for libraries consumed by other projects), and setRestoreLockedModeor--locked-modein CI. Pin the SDK withglobal.jsonso implicit package references do not break locked restores. - Signature policy:
signatureValidationMode=requirewith arepositoryentry for nuget.org restricted by<owners>, plusauthorentries for vendors you pin by certificate fingerprint. KeepallowUntrustedRoot="false". Plan for repository certificate rotation, which requires updating the policy. - NuGetAudit: enabled by default where a source provides vulnerability data; set
NuGetAuditModetoallto include transitive packages (the default for projects targetingnet10.0or later) and add nuget.org orhttps://data.nuget.org/v3/index.jsonas anauditSourcesentry if your restore uses only private feeds. - Ephemeral agents: clean the global packages folder, HTTP cache and build output after every job, including failed or cancelled ones, so authenticated-feed packages do not leak to the next job.
- Do not build from Downloads: MSBuild imports
Directory.Build.propsand similar files from every parent directory, and NuGet merges config files up the tree.
Publishers
- Author-sign packages with a code signing certificate and an RFC 3161 timestamp (nuget.org requires RSA 2048 bits or more, a certificate chaining to a root trusted by default on Windows, and rejects self-issued certificates). Author signing is supported by
nuget.exeon Windows. - Publish with Trusted Publishing or scoped expiring keys from protected CI environments only; never from developer laptops.
- Reserve your ID prefix and own packages through an organisation.
- Produce reproducible builds with Source Link so consumers can validate binaries against source.
- Deprecate and unlist vulnerable versions, and report advisories to the GitHub Advisory Database.
Rollout: add nuget.config with mapping in report-only fashion by first running restore with the new config on a branch and fixing restore failures for packages that match no pattern; then enable lock files and locked mode; then the signature policy in one pilot repository before org-wide templates. Roll back by reverting the config file, which is the only change involved. Small teams can stop after mapping, lock files and NuGetAudit; large estates should template nuget.config, enforce it with a repository policy check, and run all restores through a governed proxy.
Lessons from incidents
In December 2022, PyTorch nightly users on Linux who installed with pip could receive a malicious torchtriton package registered on PyPI under the same name as the dependency PyTorch served from its own nightly index; pip preferred the public package, and the payload collected environment variables, SSH files and host details. The registry was PyPI, not NuGet, but the failure is the one Package Source Mapping exists to prevent: a client that searches several sources and accepts whichever has the name. The NuGet equivalents of PyTorch's fixes are mapping the internal ID to the private feed, reserving the prefix on nuget.org, and registering placeholders for internal names that cannot be prefixed. See the PyTorch torchtriton breach analysis.
| Control | Stops a public package shadowing an internal one | Stops a tampered package | Stops a stolen publishing key |
|---|---|---|---|
| Package Source Mapping | Yes, at download time | No | No |
| ID prefix reservation | Yes, on nuget.org for new IDs | No | No |
| Lock file in locked mode | Partly: blocks unexpected new versions | Yes, via content hash | Partly: a new malicious version is not picked up until the lock file is updated |
Signature policy (require, owners) | Yes, if the impostor's owner is not trusted | Yes | No for repository signatures, since the attacker publishes as the real owner |
| Trusted Publishing or scoped keys | No | No | Yes: no long-lived key to steal, or limited blast radius |
No single control covers all three; the baseline above combines them.
Common misconfigurations
- Two sources, no mapping: a public package with an internal name wins restore. See the Malicious Package and Dependency Confusion Guide.
- Mapping without
<clear />: a user-levelnuget.configadds an extra source the repository never intended. - Shared global packages folder on build agents: a package cached from an earlier build bypasses mapping and signature changes.
- "Signed" assumed to mean trusted: without
requiremode, packages signed with untrusted certificates install like unsigned packages. - Lock file committed, locked mode off: CI regenerates the lock file and the protection disappears.
- Legacy full-scope API key in a CI variable: never expires and can push every package the account owns.
- Audit blind spot: private-only sources with no
auditSources, so NuGetAudit has no vulnerability data and only NU1905 hints at it.
Framework mapping
| Framework | Reference | NuGet control |
|---|---|---|
| MITRE ATT&CK | T1195.001 Compromise Software Dependencies and Development Tools | Source mapping, lock files, signature policy, prefix reservation |
| NIST SP 800-53 Rev. 5 | SR-3, SR-4, SR-11, SI-7, IA-5 | Supply chain controls, provenance, component authenticity, integrity, authenticator management for API keys |
| NIST CSF 2.0 | ID.RA-01, PR.PS-02, GV.SC-05 | NuGetAudit findings, patching dependencies, supplier requirements |
| NIST SP 800-218 SSDF | PS.2, PW.4 | Verifiable release integrity; reuse of well-secured components |
| OWASP CI/CD Top 10 | CICD-SEC-3 Dependency Chain Abuse | Mapping, locked restores, proxy feeds |
Practitioner checklist
- Every repository has one root
nuget.configwith<clear />under sources and a completepackageSourceMapping. - Internal package IDs share a prefix that is mapped to the private feed and reserved on nuget.org.
- Applications commit
packages.lock.jsonand CI restores with--locked-mode; the SDK is pinned inglobal.json. signatureValidationModeisrequirewith explicittrustedSignerswhere the dependency set allows it.- NuGetAudit runs in
allmode with a vulnerability-capable audit source; NU1903 and NU1904 fail the build; suppressions have owners and expiry. - Build agents are ephemeral or clean caches and output after every job.
- Packages are published via Trusted Publishing or scoped, expiring keys from protected environments; no legacy keys remain.
- Production packages are owned by an organisation with a small, reviewed administrator list.
- Feed credentials never appear as literals in committed config files.
Standards and references
- Microsoft Learn: Best practices for a secure software supply chain (NuGet)
- Microsoft Learn: Package Source Mapping
- Microsoft Learn: PackageReference in project files (locking dependencies)
- Microsoft Learn: Manage package trust boundaries
- Microsoft Learn: Auditing package dependencies for security vulnerabilities
- Microsoft Learn: Trusted Publishing on nuget.org
- Microsoft Learn: Scoped API keys
- Microsoft Learn: Package ID prefix reservation
Related NHI Mgmt Group resources: .NET Security Guide · Package Registry Security Comparison Guide · OWASP CI/CD Top 10 CICD-SEC-3 Dependency Chain Abuse Guide · SBOM Guide