跳到主要内容

.NET: The certificate chain was issued by an authority that is not trusted

What the error actually means

The message surfaces in two shapes depending on the runtime. On modern .NET (SocketsHttpHandler / HttpClient) you get the inner exception with the specific chain flag:

System.Net.Http.HttpRequestException: The SSL connection could not be established, see inner exception.
 ---> System.Security.Authentication.AuthenticationException: The remote certificate is invalid because of errors in the certificate chain: UntrustedRoot

On .NET Framework and anything going through Windows SChannel, you get the Win32 wording:

System.Net.WebException: The underlying connection was closed: Could not establish trust relationship for the SSL/TLS secure channel.
 ---> System.Security.Authentication.AuthenticationException: The remote certificate is invalid according to the validation procedure.

The certificate chain was issued by an authority that is not trusted. is the localized text of Win32 error 0x800B0109 (CERT_E_UNTRUSTEDROOT). The TLS handshake itself succeeded — the server proved possession of its private key — but X509Chain.Build() could not terminate the path at a self-signed root present in the Trusted Root Certification Authorities store.

Three root causes need three different fixes:

  1. Client-side trust gap — a self-signed cert or private CA is not installed on the client (Windows cert store, Linux ca-certificates bundle, macOS Keychain).
  2. Server-side chain gap — the server sends only its leaf certificate and omits the intermediate, so the client cannot build the path even though it trusts the root.
  3. Expired / wrong-host / revoked — often reported alongside UntrustedRoot when the root is missing. Fix the real defect; do not blanket-skip validation.

Quick triage: if openssl s_client reports verify error:num=20:unable to get local issuer certificate, it is cause #2 (missing intermediate). If it reports num=19:self-signed certificate in certificate chain against a public hostname, the server is misconfigured too.

Step 0: Diagnose before you change anything

Get the chain the server actually sends, then compare it with what your client can build.

# What the server sends (leaf + intermediates)
openssl s_client -connect api.internal.example.com:443 -servername api.internal.example.com -showcerts </dev/null

# Verify against the local trust store
openssl s_client -connect api.internal.example.com:443 -servername api.internal.example.com </dev/null 2>&1 
  | openssl verify -CAfile /etc/ssl/certs/ca-certificates.crt

# Is the root in the bundle at all? (Linux)
awk -v cmd='openssl x509 -noout -subject' '/BEGIN/{close(cmd)};{print | cmd}' < /etc/ssl/certs/ca-certificates.crt 
  | grep -i "My Company Root CA"

# Windows: list the trusted root store
certutil -store Root | findstr /i "My Company Root CA"

# macOS: system keychain
security find-certificate -a -c "My Company Root CA" -p /Library/Keychains/System.keychain

Then make .NET tell you the truth instead of guessing. This callback is the fastest feedback loop you will get — errors flips to None the moment the trust is fixed:

using System.Net.Security;
using System.Security.Cryptography.X509Certificates;

var handler = new HttpClientHandler
{
    ServerCertificateCustomValidationCallback = (request, cert, chain, errors) =>
    {
        Console.WriteLine($"Subject : {cert?.Subject}");
        Console.WriteLine($"Issuer  : {cert?.Issuer}");
        Console.WriteLine($"Errors  : {errors}");

        if (chain is not null)
        {
            foreach (var element in chain.ChainElements)
                Console.WriteLine($"  chain: {element.Certificate.Subject}");

            foreach (var status in chain.ChainStatus)
                Console.WriteLine($"  status: {status.Status} - {status.StatusInformation.Trim()}");
        }
        return errors == SslPolicyErrors.None;
    }
};

var client = new HttpClient(handler);

Fix 1: Install the root CA on Windows

Two stores matter. LocalMachineRoot is what Windows Services, IIS app pools running as AppPoolIdentity/SYSTEM, and scheduled tasks see. CurrentUserRoot only covers console apps and interactive tests. Most “I imported it and nothing changed” reports are a store mismatch.

GUI: certmgr.msc (current user) or certlm.msc (local machine) → Trusted Root Certification Authorities → Certificates → right-click → All Tasks → Import → select root-ca.cer.

Command line, machine-wide (elevated prompt):

certutil -addstore -f Root C:certsroot-ca.cer
certutil -store Root | findstr /i "My Company Root CA"

PowerShell equivalent:

Import-Certificate -FilePath C:certsroot-ca.cer -CertStoreLocation Cert:LocalMachineRoot
Get-ChildItem Cert:LocalMachineRoot | Where-Object Subject -like "*My Company Root CA*"

If the machine is domain-joined, a manual import can be overwritten at the next policy refresh. Push the root through the Trusted Root Certification Authorities GPO instead of scripting it per server.

For local ASP.NET Core development the self-signed Kestrel certificate is a separate mechanism:

dotnet dev-certs https --clean
dotnet dev-certs https --trust
dotnet dev-certs https --check --verbose

--trust is not supported on every Linux distribution. Where it fails, the cert lands in ~/.dotnet/corefx/cryptography/x509stores/my and must be trusted manually — or use the SSL_CERT_FILE approach in the next section.

Fix 2: Install the root CA on Linux, containers, and macOS

Debian / Ubuntu

sudo cp root-ca.crt /usr/local/share/ca-certificates/mycompany-root-ca.crt
sudo update-ca-certificates
# expect: 1 added, 0 removed; done.
ls -l /etc/ssl/certs | grep -i mycompany

RHEL / Fedora / Amazon Linux

sudo cp root-ca.crt /etc/pki/ca-trust/source/anchors/mycompany-root-ca.crt
sudo update-ca-trust extract
trust list | grep -i "my company root ca"

Alpine

apk add --no-cache ca-certificates
cp root-ca.crt /usr/local/share/ca-certificates/mycompany-root-ca.crt
update-ca-certificates

The mcr.microsoft.com/dotnet/runtime:8.0-alpine family ships without the ca-certificates package. That one missing package produces UntrustedRoot for every public HTTPS call, not just your internal CA — a very common container-only failure. Bake it into the image:

FROM mcr.microsoft.com/dotnet/aspnet:8.0-alpine
RUN apk add --no-cache ca-certificates 
 && cp /src/root-ca.crt /usr/local/share/ca-certificates/ 
 && update-ca-certificates
COPY --from=build /app /app
WORKDIR /app
ENTRYPOINT ["dotnet", "MyApp.dll"]

Debian-slim equivalent:

RUN apt-get update && apt-get install -y --no-install-recommends ca-certificates 
 && cp /src/root-ca.crt /usr/local/share/ca-certificates/ 
 && update-ca-certificates 
 && rm -rf /var/lib/apt/lists/*

.NET on Linux reads OpenSSL’s default paths (/etc/ssl/certs, /etc/pki/tls/certs). For a single app without touching the system bundle, point it at a merged PEM:

export SSL_CERT_FILE=/opt/certs/my-bundle.pem
export SSL_CERT_DIR=/etc/ssl/certs

Verify from inside the container before blaming .NET:

openssl s_client -connect api.internal.example.com:443 -CAfile /etc/ssl/certs/ca-certificates.crt </dev/null
dotnet --info

macOS

sudo security add-trusted-cert -d -r trustRoot 
  -k /Library/Keychains/System.keychain root-ca.crt
security find-certificate -a -c "My Company Root CA" -p /Library/Keychains/System.keychain | head -1

Use -d to target the admin (system) domain. A certificate trusted only in your login keychain will not be trusted by a launchd daemon or a CI agent running under another user.

Fix 3: Trust a private CA in code without disabling validation

The temptation is return true;. Do not. It disables hostname checks, expiry checks, and revocation checks for every connection on that handler, and it survives code review exactly once.

If you must pin a private root at runtime, extend the chain engine with X509ChainPolicy.CustomTrustStore plus X509ChainTrustMode.CustomRootTrust (.NET 5+). Hostname and expiry validation stay intact, and only your root is trusted:

using System.Net.Security;
using System.Security.Cryptography.X509Certificates;

static HttpClient CreatePinnedClient(string rootCaPath, string expectedHost)
{
    var root = new X509Certificate2(rootCaPath); // root-ca.crt

    var handler = new HttpClientHandler
    {
        ServerCertificateCustomValidationCallback = (request, cert, chain, errors) =>
        {
            if (cert is null) return false;
            if (!string.Equals(request.RequestUri?.Host, expectedHost, StringComparison.OrdinalIgnoreCase))
                return false;

            using var custom = new X509Chain();
            custom.ChainPolicy.TrustMode = X509ChainTrustMode.CustomRootTrust;
            custom.ChainPolicy.CustomTrustStore.Add(root);
            custom.ChainPolicy.RevocationMode = X509RevocationMode.NoCheck; // offline internal CA
            custom.ChainPolicy.VerificationFlags = X509VerificationFlags.NoFlag;

            var ok = custom.Build(new X509Certificate2(cert));
            if (!ok)
                foreach (var s in custom.ChainStatus)
                    Console.WriteLine($"{s.Status}: {s.StatusInformation.Trim()}");

            return ok;
        }
    };

    return new HttpClient(handler);
}

Three details that bite people:

  • CustomRootTrust replaces the OS root store for that chain object only. Public roots are no longer trusted by that chain — which is precisely what pinning means.
  • Adding to CustomTrustStore without setting TrustMode silently does nothing.
  • The intermediate must still be reachable, either from the server’s handshake or added explicitly: custom.ChainPolicy.ExtraStore.Add(new X509Certificate2("intermediate.crt"));

For gRPC, the same delegate hangs off SocketsHttpHandler.SslOptions.RemoteCertificateValidationCallback; for WCF and HttpWebRequest on .NET Framework, the hook is ServicePointManager.ServerCertificateValidationCallback — but .NET Framework has no CustomRootTrust, so install the root in the store instead.

Fix 4: The server may be the one at fault

Public CAs are trusted by default. If a public site throws UntrustedRoot for all clients, the server is almost certainly sending an incomplete chain — the classic nginx/IIS mistake of serving the leaf but not the intermediate.

openssl s_client -connect www.example.com:443 -servername www.example.com -showcerts </dev/null 2>&1 
  | grep -E "^(depth|verify| [0-9]+ s:)"

Symptom of a missing intermediate:

depth=1 CN = Example Intermediate CA
verify error:num=20:unable to get local issuer certificate
verify return:1

Windows clients often work anyway because CryptoAPI fetches the intermediate via AIA (authority information access). Linux and .NET on Linux do not, so the same URL fails only inside your container. That asymmetry is the tell.

nginx — concatenate leaf then intermediate into one file:

cat server.crt intermediate.crt > fullchain.crt
# nginx.conf
ssl_certificate     /etc/nginx/certs/fullchain.crt;
ssl_certificate_key /etc/nginx/certs/server.key;

IIS — install the intermediate into the CA store, then re-bind the site, or complete the pending request with the full .p7b chain:

certutil -addstore -f CA intermediate.cer

Confirm the fix end-to-end:

openssl s_client -connect www.example.com:443 -servername www.example.com 
  -CAfile /etc/ssl/certs/ca-certificates.crt </dev/null 2>&1 | grep "Verify return code"
# want: Verify return code: 0 (ok)

Comparison: which fix applies to which situation

Situation Where the trust gap is Fix Scope Persistence
Self-signed cert on an internal service, Windows client Client machine/user root store certutil -addstore -f Root or certlm.msc All apps on that machine Until reimage or GPO refresh
Same, Linux host OpenSSL trust bundle /usr/local/share/ca-certificates + update-ca-certificates All OpenSSL/.NET apps Survives until host rebuild
Container image missing the CA bundle entirely No ca-certificates package apk add ca-certificates / apt install ca-certificates Whole image Baked into Dockerfile
One app must trust a private root, no admin rights App-level chain policy CustomRootTrust + CustomTrustStore That HttpClient only In code/config
Public site fails for every client Server sends no intermediate Serve fullchain / install intermediate All clients Server config
Local Kestrel development Dev cert not trusted dotnet dev-certs https --trust Dev machine User profile
Any of the above, “fixed” with return true None — validation disabled Do not Security hole Forever

Troubleshooting: real error messages and what they mean

Message Meaning Action
The remote certificate is invalid because of errors in the certificate chain: UntrustedRoot Chain built to a self-signed root that is not in the trust store Install the root (Fix 1/2) or use CustomRootTrust
The certificate chain was issued by an authority that is not trusted. (0x800B0109) Same condition, SChannel wording Confirm you imported into LocalMachineRoot, not just CurrentUser
PartialChain in ChainStatus Missing intermediate — the root may be fine Fix 4: serve the fullchain
RemoteCertificateNameMismatch Cert CN/SAN does not match the host in the URL Reissue with the correct SAN; check you are not calling an IP address
RemoteCertificateChainErrors plus NotTimeValid Expired leaf, intermediate, or root Renew; expired roots break everything silently
System.Security.Authentication.AuthenticationException: The remote certificate is invalid according to the validation procedure. .NET Framework generic wrapper hiding the real flag Add the logging callback from Step 0
Unable to load shared library libssl.so, or handshake fails only in Alpine Missing OpenSSL / CA package in the image apk add ca-certificates openssl
curl: (60) SSL certificate problem: unable to get local issuer certificate Client-side, not .NET — a useful cross-check If curl fails too, it is the store or the server, not your code
NU1301 / dotnet restore fails against an internal NuGet feed NuGet uses the same trust store Install the root for the build agent account, then restart the agent

Two traps worth calling out:

  • It worked yesterday. Check root expiry, and check whether a GPO or update-ca-certificates run replaced the bundle. Also check that an image tag did not quietly move from debian to alpine.
  • Only HttpClient fails, the browser is fine. Browsers have their own stores and do AIA fetching. Your app pool identity or service account has a different root store than your interactive login — reproduce as that account.

FAQ

Is it safe to set ServerCertificateCustomValidationCallback = (…) => true?

No. It disables hostname verification, expiry checks, and revocation for every request on that handler, turning TLS into encryption without authentication. Use CustomRootTrust or install the root in the store.

Why does it work with curl but not with my .NET app?

Different trust sources. .NET on Linux reads OpenSSL’s default bundle; on Windows it reads CryptoAPI stores that depend on the account. If curl succeeds, diff curl -v output against the ChainStatus logging from Step 0.

I installed the root but still get UntrustedRoot. Why?

Usually one of: wrong store (CurrentUser vs LocalMachine), the process was already running and needs a restart, you imported the intermediate instead of the root, or a GPO overwrote it. Verify with certutil -store Root or trust list.

Does dotnet dev-certs https --trust fix this for internal APIs?

No. It only trusts the ASP.NET Core development certificate used by Kestrel on localhost. A private CA or a corporate server certificate needs the normal root-store installation.

Do I need to add the intermediate to the trusted root store?

No. Only roots belong in the trusted root store. Intermediates belong in the server’s chain (fullchain) or in ChainPolicy.ExtraStore for code-level pinning.

How do I make this work in Kubernetes?

Bake the CA into the image at build time, or mount a ConfigMap/Secret containing the PEM and point SSL_CERT_FILE at a merged bundle (system bundle plus your root). Mounting over /etc/ssl/certs/ca-certificates.crt also works but hides the public roots, so prefer a merged file.

Will this break when the root CA expires?

Yes, and quietly — every client trusting it starts failing at once. Track root expiry with openssl x509 -enddate -noout -in root-ca.crt alongside your leaf certificate monitoring.