66 lines
1.6 KiB
Plaintext
66 lines
1.6 KiB
Plaintext
![]() |
=== How to fix it in .NET
|
||
|
|
||
|
The following code is vulnerable to deserialization attacks because it
|
||
|
deserializes HTTP data without validating it first.
|
||
|
|
||
|
[cols="a"]
|
||
|
|===
|
||
|
h| Non-compliant code example
|
||
|
|
|
||
|
[source,csharp]
|
||
|
----
|
||
|
public class Example : Controller
|
||
|
{
|
||
|
[HttpPost]
|
||
|
public ActionResult Deserialize(HttpPostedFileBase inputFile)
|
||
|
{
|
||
|
ExpectedType expectedObject = null;
|
||
|
var formatter = new BinaryFormatter();
|
||
|
expectedObject = (ExpectedType)formatter.Deserialize(inputFile.InputStream);
|
||
|
}
|
||
|
}
|
||
|
----
|
||
|
h| Compliant solution
|
||
|
|
|
||
|
[source,csharp]
|
||
|
----
|
||
|
public class Example : Controller
|
||
|
{
|
||
|
[HttpPost]
|
||
|
public ActionResult Deserialize(HttpPostedFileBase inputFile)
|
||
|
{
|
||
|
ExpectedType expectedObject = null;
|
||
|
JsonSerializer serializer = new JsonSerializer(typeof(expectedObject));
|
||
|
expectedObject = (ExpectedType)serializer.Deserialize(inputFile.InputStream);
|
||
|
}
|
||
|
}
|
||
|
----
|
||
|
|===
|
||
|
|
||
|
=== How does this work?
|
||
|
|
||
|
include::../../common/fix/introduction.adoc[]
|
||
|
|
||
|
include::../../common/fix/safer-serialization.adoc[]
|
||
|
|
||
|
include::../../common/fix/integrity-check.adoc[]
|
||
|
|
||
|
include::../../common/fix/pre-approved-list.adoc[]
|
||
|
|
||
|
In the code samples, a pre-approved class is used natively by JsonSerializer to
|
||
|
validate the class during serialization.
|
||
|
XmlSerializer also provides this capability. +
|
||
|
**Note**: The pre-approved class should not tamper with the application's inner
|
||
|
workings.
|
||
|
|
||
|
The following native types are considered unsafe because they do not provide
|
||
|
these capabilities:
|
||
|
|
||
|
* `BinaryFormatter`
|
||
|
* `SoapFormatter`
|
||
|
* `NetDataContractSerializer`
|
||
|
* `LosFormatter`
|
||
|
* `ObjectStateFormatter`
|
||
|
|
||
|
|