Serialization check bypass¶
ID: cs/serialization-check-bypass Kind: problem Security severity: 7.8 Severity: warning Precision: medium Tags: - security - external/cwe/cwe-20 Query suites: - csharp-security-extended.qls - csharp-security-and-quality.qls
Click to see the query in the CodeQL repository
Fields that are deserialized should be validated, otherwise the deserialized object could contain invalid data.
This query finds cases where a field is validated in a constructor, but not in a deserialization method. This is an indication that the deserialization method is missing a validation step.
Recommendation¶
If a field needs to be validated, then ensure that validation is also performed during deserialization.
Example¶
The following example has the validation of the Age
field in the constructor but not in the deserialization method:
usingSystem;usingSystem.Runtime.Serialization;[Serializable]publicclassPersonBad:ISerializable{publicintAge;publicPersonBad(intage){if(age<0)thrownewArgumentException(nameof(age));Age=age;}[OnDeserializing]voidISerializable.GetObjectData(SerializationInfoinfo,StreamingContextcontext){Age=info.GetInt32("age");// BAD - write is unsafe}}
The problem is fixed by adding validation to the deserialization method as follows:
usingSystem;usingSystem.Runtime.Serialization;[Serializable]publicclassPersonGood:ISerializable{publicintAge;publicPersonGood(intage){if(age<0)thrownewArgumentException(nameof(age));Age=age;}[OnDeserializing]voidISerializable.GetObjectData(SerializationInfoinfo,StreamingContextcontext){intage=info.GetInt32("age");if(age<0)thrownewSerializationException(nameof(Age));Age=age;// GOOD - write is safe}}
References¶
OWASP: Data Validation.
Common Weakness Enumeration: CWE-20.