Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

.Net Core warning No XML encryptor configured

When I start my service (API on .Net Core 2.2 in Docker container) I've got a warning:

No XML encryptor configured. Key {daa53741-8295-4c9b-ae9c-e69b003f16fa} may be persisted to storage in unencrypted form.

I didn't configure DataProtection. I've found solutions to configure DataProtection but I don't need to save this key. For me if the key will only be persisted until the application restarts - it's Ok. But I don't need to see this warning in logs

Any ideas? How can we do it?

My startup Class looks like there:

public class Startup {
  public Startup(IConfiguration configuration) {
    Configuration = configuration;
  }

  public IConfiguration Configuration { get; }

  public void ConfigureServices(IServiceCollection services) {
    services.AddMemoryCache();
    services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
    services.AddApiVersioning(o => o.ApiVersionReader = new HeaderApiVersionReader("api-version"));
  }

  public void Configure(IApplicationBuilder app, IHostingEnvironment env, IApplicationLifetime lifetime) {
    if (env.IsDevelopment()) {
      app.UseDeveloperExceptionPage();
    }

    app.UseMvc();

    lifetime.ApplicationStarted.Register(OnApplicationStarted);
    lifetime.ApplicationStopping.Register(OnShutdown);
  }

  public void OnApplicationStarted() {
    Console.Out.WriteLine($"Open Api Started");
  }

  public void OnShutdown() {
    Console.Out.WriteLine($"Open Api is shutting down.");
  }
}

Maybe it's help too my packages in the project

<ItemGroup>
    <PackageReference Include="BouncyCastle.NetCore" Version="1.8.5" />
    <PackageReference Include="Microsoft.AspNetCore.App" />
    <PackageReference Include="Microsoft.AspNetCore.Mvc.Versioning" Version="3.1.2" />
    <PackageReference Include="Microsoft.AspNetCore.Razor.Design" Version="2.2.0" PrivateAssets="All" />
    <PackageReference Include="Microsoft.VisualStudio.Azure.Containers.Tools.Targets" Version="1.5.4" />
    <PackageReference Include="Oracle.ManagedDataAccess.Core" Version="2.18.6" />
</ItemGroup>
like image 415
Igor Cova Avatar asked Apr 19 '19 11:04

Igor Cova


2 Answers

It may be a permission error but you have to sure about it. Try to log in when this error is thrown. I see many reasons to having this error in the development environment, generally file read permission or couldn't find or no file.

Wrap your main function with the below logging algorithm and see what's wrong:

public static void Main(string[] args)
{
    CurrentDirectoryHelpers.SetCurrentDirectory();

    Log.Logger = new LoggerConfiguration()
        .MinimumLevel.Information()
        .MinimumLevel.Override("Serilog", LogEventLevel.Information)
        .WriteTo.File("Logs/LogFrom_ProgramMain.txt")
        .CreateLogger();

    try
    {
        var whb = WebHost.CreateDefaultBuilder(args).UseContentRoot(Directory.GetCurrentDirectory());
        //whb... your codes    
        Log.Logger.Information("Information:blabla");
    }
    catch(Exception ex)
    {
        Log.Logger.Error("Main handled an exception: " + ex.Message);
    }
}

Don't palter trust the code, and see.

You can use this helper method if you need:

internal class CurrentDirectoryHelpers
{
    internal const string AspNetCoreModuleDll = "aspnetcorev2_inprocess.dll";

    [System.Runtime.InteropServices.DllImport("kernel32.dll")]
    private static extern IntPtr GetModuleHandle(string lpModuleName);

    [System.Runtime.InteropServices.DllImport(AspNetCoreModuleDll)]
    private static extern int http_get_application_properties(ref IISConfigurationData iiConfigData);

    [System.Runtime.InteropServices.StructLayout(System.Runtime.InteropServices.LayoutKind.Sequential)]
    private struct IISConfigurationData
    {
        public IntPtr pNativeApplication;
        [System.Runtime.InteropServices.MarshalAs(System.Runtime.InteropServices.UnmanagedType.BStr)]
        public string pwzFullApplicationPath;
        [System.Runtime.InteropServices.MarshalAs(System.Runtime.InteropServices.UnmanagedType.BStr)]
        public string pwzVirtualApplicationPath;
        public bool fWindowsAuthEnabled;
        public bool fBasicAuthEnabled;
        public bool fAnonymousAuthEnable;
    }

    public static void SetCurrentDirectory()
    {
        try
        {
            // Check if physical path was provided by ANCM
            var sitePhysicalPath = Environment.GetEnvironmentVariable("ASPNETCORE_IIS_PHYSICAL_PATH");
            if (string.IsNullOrEmpty(sitePhysicalPath))
            {
                // Skip if not running ANCM InProcess
                if (GetModuleHandle(AspNetCoreModuleDll) == IntPtr.Zero)
                {
                    return;
                }
                IISConfigurationData configurationData = default(IISConfigurationData);
                if (http_get_application_properties(ref configurationData) != 0)
                {
                    return;
                }
                sitePhysicalPath = configurationData.pwzFullApplicationPath;
            }

            Environment.CurrentDirectory = sitePhysicalPath;
        }
        catch
        {
            // ignore
        }
    }
}
like image 196
Hamit YILDIRIM Avatar answered Nov 03 '22 23:11

Hamit YILDIRIM


You can explicit configure your cryptographic algorithms in the following way in .NET 6.

using Microsoft.AspNetCore.DataProtection;
using Microsoft.AspNetCore.DataProtection.AuthenticatedEncryption;
using Microsoft.AspNetCore.DataProtection.AuthenticatedEncryption.ConfigurationModel;

...

var builder = WebApplication.CreateBuilder(args);

...

builder.Services.AddDataProtection().UseCryptographicAlgorithms(
    new AuthenticatedEncryptorConfiguration
    {
        EncryptionAlgorithm = EncryptionAlgorithm.AES_256_CBC,
        ValidationAlgorithm = ValidationAlgorithm.HMACSHA256
    });

Configure ASP.NET Core Data Protection

The default EncryptionAlgorithm is AES-256-CBC, and the default ValidationAlgorithm is HMACSHA256. The default policy can be set by a system administrator via a machine-wide policy, but an explicit call to UseCryptographicAlgorithms overrides the default policy.

Calling UseCryptographicAlgorithms allows you to specify the desired algorithm from a predefined built-in list. You don't need to worry about the implementation of the algorithm. In the scenario above, the Data Protection system attempts to use the CNG implementation of AES if running on Windows. Otherwise, it falls back to the managed System.Security.Cryptography.Aes class.

You can manually specify an implementation via a call to UseCustomCryptographicAlgorithms.

This solution will resolve the warning as well on the linux machine which on docker based.

like image 3
Mikolaj Avatar answered Nov 03 '22 23:11

Mikolaj