dotnet反序列化之并不安全的SerializationBinder
来源:岁月联盟
时间:2022-07-04
前几天看到了这篇文章,记录一下。
使用SerializationBinder
先来一个demo,用SerializationBinder限制一下反序列化的类型。
1using System;
2using System.IO;
3using System.Runtime.Serialization;
4using System.Runtime.Serialization.Formatters.Binary;
5
6namespace Serialize
7{
8 internal class Program
9 {
10 static void Main(string[] args)
11 {
12 BinaryFormatter binaryFormatter = new BinaryFormatter();
13 MemoryStream memoryStream = new MemoryStream();
14 RCE calc = new RCE("calc");
15 binaryFormatter.Serialize(memoryStream, calc);
16
17
18 memoryStream.Position = 0;
19 binaryFormatter.Binder = new MyBinder();
20 object v = binaryFormatter.Deserialize(memoryStream);
21 Console.WriteLine(v);
22 Console.ReadKey();
23 }
24 }
25
26 [Serializable]
27 class RCE
28 {
29 public string cmd;
30
31 public RCE(string cmd)
32 {
33 this.cmd = cmd;
34 }
35
36 public override string ToString()
37 {
38 return $"exec cmd:{cmd}";
39 }
40 }
41 class MyBinder