enable the flag AllowArbitraryDataSetTypeInstantiation through code

Viewed 639

In the last several days, weeks, or months, Microsoft has released a patch for the .Net framework which breaks serialization using DataSet/DataTable, if custom types are involved. See https://docs.microsoft.com/en-us/dotnet/framework/data/adonet/dataset-datatable-dataview/security-guidance . There are several methods they have provided to reenable custom type serialization.

There is a mechanism to enable specific types through code (pasted from article):

Type[] extraAllowedTypes = new Type[]
{
    typeof(Fabrikam.CustomType),
    typeof(Contoso.AdditionalCustomType)
};

AppDomain.CurrentDomain.SetData("System.Data.DataSetDefaultAllowedTypes", extraAllowedTypes);

There is also a mechanism to enable serialization/deserialization for all types, but I only see how to do this via the config file:

<configuration>
   <runtime>
      <!-- Warning: setting the following switch can introduce a security problem. -->
      <AppContextSwitchOverrides value="Switch.System.Data.AllowArbitraryDataSetTypeInstantiation=true" />
   </runtime>
</configuration>

The aforementioned security problems do not apply in my case, because the serialization is private between the several parts of my program, the serialized form is never stored, and the communication link is protected and authenticated via TLS.

Finding all the custom types I would need to whitelist would be very onerous, and deploying modified config files is also difficult in my case.

I'm looking for a way to enable custom type serialization for all types, using code. I have looked around but haven't found anything. Does anyone know how to do this?

(thanks)

1 Answers

Since there are AppContext switches available, you can set then through code instead of the config file using AppContext.SetSwitch (assuming .NET Framework 4.6.2+ or .Net Core)

AppContext.SetSwitch("Switch.System.Data.AllowArbitraryDataSetTypeInstantiation", true);

In fact, this approach is outlined further down in the documentation you linked to.

Note that you will want to do this early on, probably in your application's entry point (Main).

Related