I'm trying to upgrade a monolithic repo so that it is no longer susceptible to this NewtonsSoft.Json Exploit. I'm new to C# so maybe that's why I'm having a little trouble understanding the fix. They say
This can be done globally with he following statement:
JsonConvert.DefaultSettings = () => new JsonSerializerSettings { MaxDepth = 128 };
I think I could just set this in each classes constructor that relies on Newtonsoft, but that would create a whole lot of duplication (example below). Am I totally off, is there a cleaner way to do things?
using Newtonsoft.Json
private class MyClasss
{
public MyClass()
{
// add this line here
JsonConvert.DefaultSettings = () => new JsonSerializerSettings { MaxDepth = 128 };
// other steps
}
// other methods
}
Notes:
I'm working in a monolithic repo full of a bunch of solutions that each contain multiple projects.
We can't update to Json.NET 13.0.1 because of some external dependencies.
We are using .Net 3.1 and there seems to be about 5 entrypoints to our repo.
CodePudding user response:
JsonConvert.DefaultSettings
is a public static Func<JsonSerializerSettings>
, so you only really need to set it once, on startup.
You have a few options for doing this which should be easier than setting it in every class constructor:
You note that your monolithic repo has 5 entry points, so you could set
JsonConvert.DefaultSettings
in eachProgram.cs
.If you have some class that is used by all consumers of your monolithic repo, you could set
JsonConvert.DefaultSettings
in the static constructor for that class:public class SomeUniversallyUsedClass { static SomeUniversallyUsedClass() { // add this line here JsonConvert.DefaultSettings = () => new JsonSerializerSettings { MaxDepth = 128 }; } // Remainder of the class }
You mention you are using
.NET 6.NET Core 3.1. In c# 9.0/.NET 5 and later, you can use a module initializer to setJsonConvert.DefaultSettings
once for every module in your monolithic repo like so:internal class JsonNetModuleInitializer { [System.Runtime.CompilerServices.ModuleInitializer] public static void Initialize() { // add this line here JsonConvert.DefaultSettings = () => new JsonSerializerSettings { MaxDepth = 128 }; } }
If you are using a version earlier than .NET 5, you could still introduce
JsonNetModuleInitializer
and callJsonNetModuleInitializer.Initialize()
from your 5 entry points and/or the static constructors for your commonly used classes.Demo fiddle here.