Derek R
Derek R

Reputation: 115

Fixing the deserializing of untrusted data using C#

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.

Upvotes: 5

Views: 13848

Answers (1)

Francisco Neto
Francisco Neto

Reputation: 160

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.

Upvotes: 5

Related Questions