Fixing the deserializing of untrusted data using C#

孤者浪人 提交于 2020-08-26 06:46:22

问题


I have the following relevant C# code:

json = File.ReadAllText(path);
isStudentObject= JsonConvert.DeserializeObject<List<XXStudentCode>>(json).Any(sv => sv.SCODE.Equals(code));

My security software (static code analysis) scans our apps and it does not like the above code, namely ReadAllText part. It says that this is a "high risk deserialization of untrusted data."

So my question is this: how can I refactor this code to make the data "trusted?" I tried different validation methods and it did not work. Any help is appreciated.


回答1:


Basically search for a way of turn off the warning (through annotation or configuration file). But, before you do this, consider the implications: you should make sure that the data that you read is treated as unsecure. In other words: if, in your "XXStudentCode" object, exists some kind of flag or attribute/property that unlock things like give permission to execute some critical code or access to private things you should make sure that you do not trust the object after serialization.

Ex:

class Person
{
    public bool IsAdmin { get; set; }
    public string Name { get; set ; }
}

In the example above if the input comes with the attribute 'IsAdmin' with value true and your system treat all "Person's" with this attribute as a admin so you will have a security flaw. To overcome this you should create classes that only contains attributes and properties that you really need to read.

Fixed Ex:

class PersonModel
{

    public string Name { get; set ; }

    public Person ToPerson()
    {
        new Person { Name = Name };
    }
}

class Person
{
    public bool IsAdmin { get; set; }
    public string Name { get; set ; }
}

Now, using the PersonModel in the deserialization, the only properties that you really want will be loaded, the rest you be ignored by the serialization library. But, this will not make you free to security flaws. If the deserialization library have some kind of security issue you will be affected too.

Hope this help.



来源:https://stackoverflow.com/questions/54993669/fixing-the-deserializing-of-untrusted-data-using-c-sharp

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!