| | | 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 | | using System.Diagnostics; |
| | | 5 | | using System.Diagnostics.CodeAnalysis; |
| | | 6 | | using System.Reflection; |
| | | 7 | | using System.Runtime.Serialization; |
| | | 8 | | |
| | | 9 | | namespace System.Text.Json.Serialization.Converters |
| | | 10 | | { |
| | | 11 | | [RequiresDynamicCode(JsonSerializer.SerializationRequiresDynamicCodeMessage)] |
| | | 12 | | internal sealed class UnsupportedTypeConverterFactory : JsonConverterFactory |
| | | 13 | | { |
| | | 14 | | public override bool CanConvert(Type type) |
| | 3646 | 15 | | { |
| | | 16 | | // If a type is added, also add to the SourceGeneration project. |
| | | 17 | | |
| | 3646 | 18 | | return |
| | 3646 | 19 | | // There's no safe way to construct a Type/MemberInfo from untrusted user input. |
| | 3646 | 20 | | typeof(MemberInfo).IsAssignableFrom(type) || |
| | 3646 | 21 | | // (De)serialization of SerializationInfo is already disallowed due to Type being disallowed |
| | 3646 | 22 | | // (the two ctors on SerializationInfo take a Type, and a Type member is present when serializing). |
| | 3646 | 23 | | // Explicitly disallowing this type provides a clear exception when ctors with |
| | 3646 | 24 | | // .ctor(SerializationInfo, StreamingContext) signatures are attempted to be used for deserialization. |
| | 3646 | 25 | | // Invoking such ctors is not safe when used with untrusted user input. |
| | 3646 | 26 | | type == typeof(SerializationInfo) || |
| | 3646 | 27 | | type == typeof(IntPtr) || |
| | 3646 | 28 | | type == typeof(UIntPtr) || |
| | 3646 | 29 | | // Exclude delegates. |
| | 3646 | 30 | | typeof(Delegate).IsAssignableFrom(type); |
| | 3646 | 31 | | } |
| | | 32 | | |
| | | 33 | | public override JsonConverter CreateConverter(Type type, JsonSerializerOptions options) |
| | 0 | 34 | | { |
| | 0 | 35 | | Debug.Assert(CanConvert(type)); |
| | 0 | 36 | | return CreateUnsupportedConverterForType(type); |
| | 0 | 37 | | } |
| | | 38 | | |
| | | 39 | | internal static JsonConverter CreateUnsupportedConverterForType(Type type, string? errorMessage = null) |
| | 0 | 40 | | { |
| | 0 | 41 | | JsonConverter converter = (JsonConverter)Activator.CreateInstance( |
| | 0 | 42 | | typeof(UnsupportedTypeConverter<>).MakeGenericType(type), |
| | 0 | 43 | | BindingFlags.Instance | BindingFlags.Public, |
| | 0 | 44 | | binder: null, |
| | 0 | 45 | | args: new object?[] { errorMessage }, |
| | 0 | 46 | | culture: null)!; |
| | | 47 | | |
| | 0 | 48 | | return converter; |
| | 0 | 49 | | } |
| | | 50 | | } |
| | | 51 | | } |