60 lines
1.3 KiB
Plaintext
60 lines
1.3 KiB
Plaintext
== How to fix it in .NET
|
|
|
|
=== Code examples
|
|
|
|
include::../../common/fix/code-rationale.adoc[]
|
|
|
|
==== Noncompliant code example
|
|
|
|
[source,csharp,diff-id=1,diff-type=noncompliant]
|
|
----
|
|
[Route("NonCompliantArrayList")]
|
|
public string NonCompliantArrayList()
|
|
{
|
|
int size;
|
|
try
|
|
{
|
|
size = int.Parse(Request.Query["size"]);
|
|
}
|
|
catch (FormatException)
|
|
{
|
|
return "Number format exception while reading size";
|
|
}
|
|
ArrayList arrayList = new ArrayList(size); // Noncompliant
|
|
return size + " bytes were allocated.";
|
|
}
|
|
----
|
|
|
|
==== Compliant solution
|
|
|
|
[source,csharp,diff-id=1,diff-type=compliant]
|
|
----
|
|
public const int MAX_ALLOC_SIZE = 1024;
|
|
|
|
[Route("CompliantArrayList")]
|
|
public string CompliantArrayList()
|
|
{
|
|
int size;
|
|
try
|
|
{
|
|
size = int.Parse(Request.Query["size"]);
|
|
}
|
|
catch (FormatException)
|
|
{
|
|
return "Number format exception while reading size";
|
|
}
|
|
size = Math.Min(size, MAX_ALLOC_SIZE);
|
|
ArrayList arrayList = new ArrayList(size);
|
|
return size + " bytes were allocated.";
|
|
}
|
|
----
|
|
|
|
=== How does this work?
|
|
|
|
include::../../common/fix/upper-limit.adoc[]
|
|
|
|
Here, the example compliant code uses the `Math.Min` function to enforce a
|
|
reasonable upper bound to the allocation size. In that case, no more than 1024
|
|
bytes can be allocated at a time.
|
|
|
|
include::../../common/fix/environment-hardening.adoc[] |