2020年6月13日 星期六

BinaryFormatter()搭配SerializationBinder類別驗證許可還原序列化的類別

避免Unsafe Deserialization弱點



https://topic.alibabacloud.com/tc/a/-net-c--pilot-type-in-deserialization-using-serializationbinder_1_31_32345296.html

//SerializationBinder的執行類
class ConversionBinder : SerializationBinder
{
    public override Type BindToType(string assemblyName, string typeName)
    {
        //篩選Person類型
        //判斷是否是Person類型,如果是返回Person_ver2
        var curAssName = typeof(Program).Assembly.FullName;
        var person1 = typeof(Person).FullName;
        string finalType = typeName;
        if (assemblyName == curAssName && typeName == person1)
            finalType = typeof(Person_ver2).FullName;
        return Type.GetType(finalType + "," + assemblyName);
    }
}

    var bf = new BinaryFormatter();
    //設定自訂的SerializationBinder對象
    bf.Binder = new ConversionBinder();
    //序列化Person
    bf.Serialize(ms, p1);
ref:
https://www.slideshare.net/MSbluehat/dangerous-contents-securing-net-deserialization?from_action=save
p.27

https://owasp.org/www-community/vulnerabilities/Deserialization_of_untrusted_data

沒有留言:

張貼留言