forked from dotnet/runtime
/
TypeNameParserSamples.cs
255 lines (224 loc) · 11.2 KB
/
TypeNameParserSamples.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
using Xunit;
namespace System.Reflection.Metadata.Tests
{
public class TypeNameParserSamples
{
internal sealed class SampleSerializationBinder : SerializationBinder
{
private static TypeNameParseOptions _options;
// we could use Frozen collections here ;)
private readonly static Dictionary<string, Type> _alwaysAllowed = new()
{
{ typeof(string).FullName, typeof(string) },
{ typeof(int).FullName, typeof(int) },
{ typeof(uint).FullName, typeof(uint) },
{ typeof(long).FullName, typeof(long) },
{ typeof(ulong).FullName, typeof(ulong) },
{ typeof(double).FullName, typeof(double) },
{ typeof(float).FullName, typeof(float) },
{ typeof(bool).FullName, typeof(bool) },
{ typeof(short).FullName, typeof(short) },
{ typeof(ushort).FullName, typeof(ushort) },
{ typeof(byte).FullName, typeof(byte) },
{ typeof(char).FullName, typeof(char) },
{ typeof(DateTime).FullName, typeof(DateTime) },
{ typeof(TimeSpan).FullName, typeof(TimeSpan) },
{ typeof(Guid).FullName, typeof(Guid) },
{ typeof(Uri).FullName, typeof(Uri) },
{ typeof(DateTimeOffset).FullName, typeof(DateTimeOffset) },
{ typeof(Version).FullName, typeof(Version) },
{ typeof(Nullable).FullName, typeof(Nullable) }, // Nullable is generic!
};
private readonly Dictionary<string, Type>? _userDefined;
public SampleSerializationBinder(Type[]? allowedTypes = null)
=> _userDefined = allowedTypes?.ToDictionary(type => type.FullName);
public override Type? BindToType(string assemblyName, string typeName)
{
// Fast path for common primitive type names and user-defined type names
// that use the same syntax and casing as System.Type.FullName API.
if (TryGetTypeFromFullName(typeName, out Type type))
{
return type;
}
_options ??= new TypeNameParseOptions() // there is no need for lazy initialization, I just wanted to have everything important in one method
{
// To prevent from unbounded recursion, we set the max depth for parser options.
// By ensuring that the max depth limit is enforced, we can safely use recursion in
// GetTypeFromParsedTypeName to get arrays of arrays and generics of generics.
MaxNodes = 10
};
if (!TypeName.TryParse(typeName.AsSpan(), out TypeName parsed, _options))
{
// we can throw any exception, log the information etc
throw new InvalidOperationException($"Invalid type name: '{typeName}'");
}
if (parsed.AssemblyName is not null)
{
// The attackers may create such a payload,
// where "typeName" passed to BindToType contains the assembly name
// and "assemblyName" passed to this method contains something else
// (some garbage or a different assembly name). Example:
// typeName: System.Int32, MyHackyDll.dll
// assemblyName: mscorlib.dll
throw new InvalidOperationException($"Type name '{typeName}' contained assembly name.");
}
return GetTypeFromParsedTypeName(parsed);
}
private Type? GetTypeFromParsedTypeName(TypeName parsed)
{
if (TryGetTypeFromFullName(parsed.FullName, out Type type))
{
return type;
}
else if (parsed.IsArray)
{
TypeName arrayElementTypeName = parsed.GetElementType();
Type arrayElementType = GetTypeFromParsedTypeName(arrayElementTypeName); // recursive call allows for creating arrays of arrays etc
return parsed.IsSZArray
? arrayElementType.MakeArrayType()
: arrayElementType.MakeArrayType(parsed.GetArrayRank());
}
else if (parsed.IsConstructedGenericType)
{
TypeName genericTypeDefinitionName = parsed.GetGenericTypeDefinition();
Type genericTypeDefinition = GetTypeFromParsedTypeName(genericTypeDefinitionName);
Debug.Assert(genericTypeDefinition.IsGenericTypeDefinition);
ImmutableArray<TypeName> genericArgs = parsed.GetGenericArguments();
Type[] typeArguments = new Type[genericArgs.Length];
for (int i = 0; i < genericArgs.Length; i++)
{
typeArguments[i] = GetTypeFromParsedTypeName(genericArgs[i]); // recursive call allows for generics of generics like "List<int?>"
}
return genericTypeDefinition.MakeGenericType(typeArguments);
}
throw new ArgumentException($"{parsed.FullName} is not on the allow list.");
}
private bool TryGetTypeFromFullName(string fullName, out Type? type)
=> _alwaysAllowed.TryGetValue(fullName, out type)
|| (_userDefined is not null && _userDefined.TryGetValue(fullName, out type));
}
[Serializable]
public class CustomUserDefinedType
{
public int Integer { get; set; }
public string Text { get; set; }
public List<DateTime> ListOfDates { get; set; }
public CustomUserDefinedType[] ArrayOfCustomUserDefinedTypes { get; set; }
}
[ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsBinaryFormatterSupported))]
public void CanDeserializeCustomUserDefinedType()
{
CustomUserDefinedType parent = new()
{
Integer = 1,
Text = "parent",
ListOfDates = new List<DateTime>()
{
DateTime.Parse("02/06/2024")
},
ArrayOfCustomUserDefinedTypes = new []
{
new CustomUserDefinedType()
{
Integer = 2,
Text = "child"
}
}
};
SampleSerializationBinder binder = new(
allowedTypes:
[
typeof(CustomUserDefinedType),
typeof(List<>) // using List<DateTime> would require using type forwarding info in dictionary
]);
CustomUserDefinedType deserialized = SerializeDeserialize(parent, binder);
Assert.Equal(parent.Integer, deserialized.Integer);
Assert.Equal(parent.Text, deserialized.Text);
Assert.Equal(parent.ListOfDates.Count, deserialized.ListOfDates.Count);
for (int i = 0; i < deserialized.ListOfDates.Count; i++)
{
Assert.Equal(parent.ListOfDates[i], deserialized.ListOfDates[i]);
}
Assert.Equal(parent.ArrayOfCustomUserDefinedTypes.Length, deserialized.ArrayOfCustomUserDefinedTypes.Length);
for (int i = 0; i < deserialized.ArrayOfCustomUserDefinedTypes.Length; i++)
{
Assert.Equal(parent.ArrayOfCustomUserDefinedTypes[i].Integer, deserialized.ArrayOfCustomUserDefinedTypes[i].Integer);
Assert.Equal(parent.ArrayOfCustomUserDefinedTypes[i].Text, deserialized.ArrayOfCustomUserDefinedTypes[i].Text);
}
}
[ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsBinaryFormatterSupported))]
public void CanDeserializeDictionaryUsingNonPublicComparerType()
{
Dictionary<string, int> dictionary = new(StringComparer.CurrentCulture)
{
{ "test", 1 }
};
SampleSerializationBinder binder = new(
allowedTypes:
[
typeof(Dictionary<,>), // this could be Dictionary<string, int> to be more strict
StringComparer.CurrentCulture.GetType(), // this type is not public, this is all this test is about
typeof(Globalization.CompareOptions),
typeof(Globalization.CompareInfo),
typeof(KeyValuePair<,>), // this could be KeyValuePair<string, int> to be more strict
]);
Dictionary<string, int> deserialized = SerializeDeserialize(dictionary, binder);
Assert.Equal(dictionary, deserialized);
}
[ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsBinaryFormatterSupported))]
public void CanDeserializeArraysOfArrays()
{
int[][] arrayOfArrays = new int[10][];
for (int i = 0; i < arrayOfArrays.Length; i++)
{
arrayOfArrays[i] = Enumerable.Repeat(i, 10).ToArray();
}
SampleSerializationBinder binder = new();
int[][] deserialized = SerializeDeserialize(arrayOfArrays, binder);
Assert.Equal(arrayOfArrays.Length, deserialized.Length);
for (int i = 0; i < arrayOfArrays.Length; i++)
{
Assert.Equal(arrayOfArrays[i], deserialized[i]);
}
}
[ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsBinaryFormatterSupported))]
public void CanDeserializeListOfListOfInt()
{
List<List<int>> listOfListOfInts = new(10);
for (int i = 0; i < listOfListOfInts.Count; i++)
{
listOfListOfInts[i] = Enumerable.Repeat(i, 10).ToList();
}
SampleSerializationBinder binder = new(allowedTypes:
[
typeof(List<>)
]);
List<List<int>> deserialized = SerializeDeserialize(listOfListOfInts, binder);
Assert.Equal(listOfListOfInts.Count, deserialized.Count);
for (int i = 0; i < listOfListOfInts.Count; i++)
{
Assert.Equal(listOfListOfInts[i], deserialized[i]);
}
}
static T SerializeDeserialize<T>(T instance, SerializationBinder binder)
{
using MemoryStream bfStream = new();
BinaryFormatter bf = new()
{
Binder = binder
};
bf.Serialize(bfStream, instance);
bfStream.Position = 0;
return (T)bf.Deserialize(bfStream);
}
}
}