63 lines
1.7 KiB
Plaintext
63 lines
1.7 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.
|
|
|
|
==== Noncompliant code example
|
|
|
|
[source,csharp,diff-id=1,diff-type=noncompliant]
|
|
----
|
|
public class Example : Controller
|
|
{
|
|
[HttpPost]
|
|
public ActionResult Deserialize(HttpPostedFileBase inputFile)
|
|
{
|
|
ExpectedType expectedObject = null;
|
|
var formatter = new BinaryFormatter();
|
|
expectedObject = (ExpectedType)formatter.Deserialize(inputFile.InputStream);
|
|
}
|
|
}
|
|
----
|
|
|
|
==== Compliant solution
|
|
|
|
[source,csharp,diff-id=1,diff-type=compliant]
|
|
----
|
|
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`
|
|
|