|
| 1 | +// Licensed to the .NET Foundation under one or more agreements. |
| 2 | +// The .NET Foundation licenses this file to you under the MIT license. |
| 3 | + |
| 4 | +#pragma warning disable CA1852 // DispatchProxy classes can't be sealed |
| 5 | + |
| 6 | +using System.Reflection; |
| 7 | +using System.Security.Cryptography.X509Certificates; |
| 8 | +using NuGet.Packaging.Signing; |
| 9 | +using INuGetLogger = NuGet.Common.ILogger; |
| 10 | + |
| 11 | +namespace Aspire.Managed.NuGet; |
| 12 | + |
| 13 | +/// <summary> |
| 14 | +/// Initializes NuGet's X509 trust store from embedded trusted root PEM certificates |
| 15 | +/// for package signature verification on Linux, without writing to disk. |
| 16 | +/// </summary> |
| 17 | +internal static class TrustedRootsHelper |
| 18 | +{ |
| 19 | + /// <summary> |
| 20 | + /// Initializes the NuGet trust store with embedded trusted root certificates. |
| 21 | + /// On Linux, when DOTNET_NUGET_SIGNATURE_VERIFICATION is set to "true", NuGet requires |
| 22 | + /// certificate bundles for signature verification. The .NET SDK ships these as PEM files |
| 23 | + /// in its trustedroots directory, but aspire-managed is a single-file app without access |
| 24 | + /// to the SDK's directory structure. This method loads embedded PEM resources in memory |
| 25 | + /// and uses DispatchProxy to create IX509ChainFactory implementations that NuGet's trust |
| 26 | + /// store can use. |
| 27 | + /// </summary> |
| 28 | + /// <remarks> |
| 29 | + /// TODO: Remove this once NuGet supports a public API for configuring the trust store, |
| 30 | + /// or when it supports single-file apps. See https://github.com/dotnet/aspire/issues/15282. |
| 31 | + /// </remarks> |
| 32 | + public static void InitializeTrustStore(INuGetLogger logger) |
| 33 | + { |
| 34 | + if (!OperatingSystem.IsLinux()) |
| 35 | + { |
| 36 | + // On Windows, NuGet uses the system certificate store directly. |
| 37 | + // On macOS, matching .NET SDK behavior which only enables this on Linux. |
| 38 | + return; |
| 39 | + } |
| 40 | + |
| 41 | + var envValue = Environment.GetEnvironmentVariable("DOTNET_NUGET_SIGNATURE_VERIFICATION"); |
| 42 | + if (!string.Equals(bool.TrueString, envValue, StringComparison.OrdinalIgnoreCase)) |
| 43 | + { |
| 44 | + // If DOTNET_NUGET_SIGNATURE_VERIFICATION is not set to "true", NuGet won't |
| 45 | + // perform signature verification on Linux, so there's no need to initialize |
| 46 | + // the trust store. |
| 47 | + return; |
| 48 | + } |
| 49 | + |
| 50 | + try |
| 51 | + { |
| 52 | + InitializeTrustStoreFromEmbeddedResources(logger); |
| 53 | + } |
| 54 | + catch (Exception ex) |
| 55 | + { |
| 56 | + // Log but don't fail the restore. If trust store initialization fails, |
| 57 | + // NuGet may still work if signature verification is not required or if |
| 58 | + // the system has its own certificate bundles. |
| 59 | + logger.LogWarning($"Failed to initialize NuGet trust store from embedded certificates: {ex.Message}"); |
| 60 | + } |
| 61 | + } |
| 62 | + |
| 63 | + private static void InitializeTrustStoreFromEmbeddedResources(INuGetLogger logger) |
| 64 | + { |
| 65 | + var nugetPackagingAssembly = typeof(X509TrustStore).Assembly; |
| 66 | + |
| 67 | + // Resolve internal NuGet types needed for DispatchProxy creation |
| 68 | + var chainFactoryInterfaceType = nugetPackagingAssembly.GetType("NuGet.Packaging.Signing.IX509ChainFactory"); |
| 69 | + var chainInterfaceType = nugetPackagingAssembly.GetType("NuGet.Packaging.Signing.IX509Chain"); |
| 70 | + |
| 71 | + if (chainFactoryInterfaceType is null || chainInterfaceType is null) |
| 72 | + { |
| 73 | + logger.LogWarning("Could not find IX509ChainFactory or IX509Chain types in NuGet.Packaging."); |
| 74 | + return; |
| 75 | + } |
| 76 | + |
| 77 | + // Set up code signing trust store |
| 78 | + SetTrustStoreFactory( |
| 79 | + "SetCodeSigningX509ChainFactory", |
| 80 | + "codesignctl.pem", |
| 81 | + chainFactoryInterfaceType, |
| 82 | + chainInterfaceType, |
| 83 | + logger); |
| 84 | + |
| 85 | + // Set up timestamping trust store |
| 86 | + SetTrustStoreFactory( |
| 87 | + "SetTimestampingX509ChainFactory", |
| 88 | + "timestampctl.pem", |
| 89 | + chainFactoryInterfaceType, |
| 90 | + chainInterfaceType, |
| 91 | + logger); |
| 92 | + } |
| 93 | + |
| 94 | + private static void SetTrustStoreFactory( |
| 95 | + string setterMethodName, |
| 96 | + string resourceName, |
| 97 | + Type chainFactoryInterfaceType, |
| 98 | + Type chainInterfaceType, |
| 99 | + INuGetLogger logger) |
| 100 | + { |
| 101 | + var certificates = LoadCertificatesFromResource(resourceName); |
| 102 | + if (certificates is null || certificates.Count == 0) |
| 103 | + { |
| 104 | + logger.LogWarning($"No certificates loaded from embedded resource: {resourceName}"); |
| 105 | + return; |
| 106 | + } |
| 107 | + |
| 108 | + // Create IX509ChainFactory proxy via DispatchProxy |
| 109 | + var factory = ChainFactoryDispatchProxy.CreateFactory( |
| 110 | + chainFactoryInterfaceType, chainInterfaceType, certificates); |
| 111 | + |
| 112 | + // Call the setter on X509TrustStore to register the factory |
| 113 | + var setter = typeof(X509TrustStore).GetMethod( |
| 114 | + setterMethodName, |
| 115 | + BindingFlags.NonPublic | BindingFlags.Static); |
| 116 | + |
| 117 | + if (setter is null) |
| 118 | + { |
| 119 | + logger.LogWarning($"Could not find {setterMethodName} on X509TrustStore."); |
| 120 | + return; |
| 121 | + } |
| 122 | + |
| 123 | + setter.Invoke(null, [factory]); |
| 124 | + logger.LogInformation($"Initialized NuGet trust store from embedded resource: {resourceName} ({certificates.Count} certificates)"); |
| 125 | + } |
| 126 | + |
| 127 | + private static X509Certificate2Collection? LoadCertificatesFromResource(string resourceName) |
| 128 | + { |
| 129 | + using var stream = typeof(TrustedRootsHelper).Assembly.GetManifestResourceStream(resourceName); |
| 130 | + if (stream is null) |
| 131 | + { |
| 132 | + return null; |
| 133 | + } |
| 134 | + |
| 135 | + using var reader = new StreamReader(stream); |
| 136 | + var pemContents = reader.ReadToEnd(); |
| 137 | + |
| 138 | + var certificates = new X509Certificate2Collection(); |
| 139 | + certificates.ImportFromPem(pemContents); |
| 140 | + return certificates; |
| 141 | + } |
| 142 | +} |
| 143 | + |
| 144 | +/// <summary> |
| 145 | +/// DispatchProxy that implements NuGet's internal IX509ChainFactory interface. |
| 146 | +/// Creates X509Chain instances configured with custom root trust using embedded certificates. |
| 147 | +/// </summary> |
| 148 | +internal class ChainFactoryDispatchProxy : DispatchProxy |
| 149 | +{ |
| 150 | + private X509Certificate2Collection _certificates = []; |
| 151 | + private Type _chainInterfaceType = null!; |
| 152 | + |
| 153 | + internal static object CreateFactory( |
| 154 | + Type chainFactoryInterfaceType, |
| 155 | + Type chainInterfaceType, |
| 156 | + X509Certificate2Collection certificates) |
| 157 | + { |
| 158 | + var proxy = (ChainFactoryDispatchProxy)Create(chainFactoryInterfaceType, typeof(ChainFactoryDispatchProxy)); |
| 159 | + |
| 160 | + proxy._certificates = certificates; |
| 161 | + proxy._chainInterfaceType = chainInterfaceType; |
| 162 | + return proxy; |
| 163 | + } |
| 164 | + |
| 165 | + protected override object? Invoke(MethodInfo? targetMethod, object?[]? args) |
| 166 | + { |
| 167 | + // IX509ChainFactory has a single method: IX509Chain Create() |
| 168 | + if (targetMethod?.Name == "Create") |
| 169 | + { |
| 170 | + return CreateChain(); |
| 171 | + } |
| 172 | + |
| 173 | + throw new NotSupportedException($"Method {targetMethod?.Name} is not supported."); |
| 174 | + } |
| 175 | + |
| 176 | + private object CreateChain() |
| 177 | + { |
| 178 | + // Create an IX509Chain proxy that wraps an X509Chain with custom root trust |
| 179 | + return ChainDispatchProxy.CreateChain(_chainInterfaceType, _certificates); |
| 180 | + } |
| 181 | +} |
| 182 | + |
| 183 | +/// <summary> |
| 184 | +/// DispatchProxy that implements NuGet's internal IX509Chain interface. |
| 185 | +/// Wraps an X509Chain configured with CustomRootTrust mode. |
| 186 | +/// </summary> |
| 187 | +internal class ChainDispatchProxy : DispatchProxy |
| 188 | +{ |
| 189 | + private readonly X509Chain _chain = new(); |
| 190 | + |
| 191 | + internal static object CreateChain( |
| 192 | + Type chainInterfaceType, |
| 193 | + X509Certificate2Collection certificates) |
| 194 | + { |
| 195 | + var proxy = (ChainDispatchProxy)Create(chainInterfaceType, typeof(ChainDispatchProxy)); |
| 196 | + |
| 197 | + proxy._chain.ChainPolicy.TrustMode = X509ChainTrustMode.CustomRootTrust; |
| 198 | + proxy._chain.ChainPolicy.CustomTrustStore.AddRange(certificates); |
| 199 | + return proxy; |
| 200 | + } |
| 201 | + |
| 202 | + protected override object? Invoke(MethodInfo? targetMethod, object?[]? args) |
| 203 | + { |
| 204 | + return targetMethod?.Name switch |
| 205 | + { |
| 206 | + "Build" => Build((X509Certificate2)args![0]!), |
| 207 | + "Dispose" => Dispose(), |
| 208 | + "get_ChainElements" => _chain.ChainElements, |
| 209 | + "get_ChainPolicy" => _chain.ChainPolicy, |
| 210 | + "get_ChainStatus" => _chain.ChainStatus, |
| 211 | + "get_PrivateReference" => _chain, |
| 212 | + "get_AdditionalContext" => (global::NuGet.Common.ILogMessage?)null, |
| 213 | + _ => throw new NotSupportedException($"Method {targetMethod?.Name} is not supported.") |
| 214 | + }; |
| 215 | + } |
| 216 | + |
| 217 | + private bool Build(X509Certificate2 certificate) |
| 218 | + { |
| 219 | + return _chain.Build(certificate); |
| 220 | + } |
| 221 | + |
| 222 | + private object? Dispose() |
| 223 | + { |
| 224 | + _chain.Dispose(); |
| 225 | + return null; |
| 226 | + } |
| 227 | +} |
0 commit comments