[Fork] [Fork] questions/49038055/external-json-vulnerable-because-of-json-net-typenamehandling-auto

CSharp · Console

/Program.cs

using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.Serialization.Formatters;
using System.IO;
using System.Data;
using System.ComponentModel.DataAnnotations;
using System.Globalization;
using System.Dynamic;
using System.Threading;

using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json.Converters;
using Newtonsoft.Json.Serialization;	

    // https://stackoverflow.com/questions/49038055/external-json-vulnerable-because-of-json-net-typenamehandling-auto
    public class MyData
    {
    }

    [Serializable]
    public class MyAttackGadget : IDisposable
    {
        [NonSerialized]
        bool suppress;

        static volatile int hackCount;

        public static int HackCount { get { return hackCount; } }

        public MyAttackGadget()
        {
        }

        public MyAttackGadget(bool suppress)
        {
            this.suppress = suppress;
            if (!suppress)
            {
                Console.WriteLine("I was constructed!");
            }
        }

        protected virtual void Dispose(bool disposing)
        {
            if (!suppress)
            {
                Interlocked.Increment(ref hackCount);
            }
        }

        public void Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        }

        ~MyAttackGadget()
        {
            Dispose(false);
        }
    }

    public class RootObject<T>
    {
        public T Data { get; set; }
    }

    public class DataCollection : CollectionBase
    {

        public MyData this[int index]
        {
            get
            {
                return ((MyData)List[index]);
            }
            set
            {
                List[index] = value;
            }
        }

        public int Add(MyData value)
        {
            return (List.Add(value));
        }

        public int IndexOf(MyData value)
        {
            return (List.IndexOf(value));
        }

        public void Insert(int index, MyData value)
        {
            List.Insert(index, value);
        }

        public void Remove(MyData value)
        {
            List.Remove(value);
        }

        public bool Contains(MyData value)
        {
            // If value is not of type MyData, this will return false.
            return (List.Contains(value));
        }

        protected override void OnInsert(int index, Object value)
        {
            // Insert additional code to be run only when inserting values.
        }

        protected override void OnRemove(int index, Object value)
        {
            // Insert additional code to be run only when removing values.
        }

        protected override void OnSet(int index, Object oldValue, Object newValue)
        {
            // Insert additional code to be run only when setting values.
        }

        protected override void OnValidate(Object value)
        {
            if (value.GetType() != typeof(MyData))
                throw new ArgumentException("value must be of type MyData.", "value");
        }
    }

    class TestClass
    {
        public static void Test()
        {
            TestCollection();
        }

        static void TestCollection()
        {
            var collection = new DataCollection();
            collection.Add(new MyData());
            DoTest<DataCollection, DataCollection>(collection, s => s.Replace("MyData", "MyAttackGadget"));
        }

        static void TestException()
        {
            var exception = new Exception("naughty exception");
            exception.Data.Add("foo", new MyAttackGadget(true));

            var root = new RootObject<Exception> { Data = exception };

            DoTest(root);
        }

        private static void DoTest<T>(T root) where T : class
        {
            DoTest<T, T>(root, null);
        }

        private static void DoTest<TSerialize, TDeserialize>(TSerialize root, Func<string, string> replace) 
            where TSerialize : class
            where TDeserialize : class
        {
            var outputSettings = new JsonSerializerSettings()
            {
                TypeNameHandling = TypeNameHandling.All,
                TypeNameAssemblyFormat = FormatterAssemblyStyle.Full,
            };

            var inputSettings = new JsonSerializerSettings()
            {
                TypeNameHandling = TypeNameHandling.Auto,
                TypeNameAssemblyFormat = FormatterAssemblyStyle.Full,
            };

            var json = JsonConvert.SerializeObject(root, outputSettings);

            var naughtyJson = (replace == null ? json : replace(json));

            //Console.WriteLine(naughtyJson);

            var hackCount = MyAttackGadget.HackCount;
            try
            {
				Console.WriteLine("Deserializing an object of type {0} with the following JSON:", typeof(TDeserialize));
				Console.WriteLine(naughtyJson);
                var root2 = JsonConvert.DeserializeObject<TDeserialize>(naughtyJson, inputSettings);
                root2 = null;
            }
            catch (Exception ex)
            {
                Console.WriteLine("Caught expected exception: " + ex.Message);
            }
            GC.Collect();
            GC.WaitForPendingFinalizers();
            GC.Collect();
            GC.WaitForPendingFinalizers();

            if (MyAttackGadget.HackCount > hackCount)
                Console.WriteLine("\n**********************I was hacked!  Attack successful!**************************");
        }
    }

	public class Program
	{
		public static void Main()
		{
			Console.WriteLine("Environment version: " + Environment.Version);
			Console.WriteLine("Json.NET version: " + typeof(JsonSerializer).Assembly.FullName);
			Console.WriteLine();

			try
			{
				TestClass.Test();
			}
			catch (Exception ex)
			{
				Console.WriteLine("Failed with unhandled exception: ");
				Console.WriteLine(ex);
				throw;
			}
		}
	}

    public class AssertionFailedException : System.Exception
    {
        public AssertionFailedException() : base() { }

        public AssertionFailedException(string s) : base(s) { }
    }

    public static class Assert
    {
        public static void IsTrue(bool value)
        {
            IsTrue(value, "failed");
        }

        public static void IsTrue(bool value, string message)
        {
            if (value == false)
                throw new AssertionFailedException(message ?? "failed");
        }
    }
;