Using unsafe
code blocks can lead to unintended security or stability risks.
unsafe
code blocks allow developers to use features such as pointers, fixed buffers, function calls through pointers and manual memory
management. Such features may be necessary for interoperability with native libraries, as these often require pointers. It may also increase
performance in some critical areas, as certain bounds checks are not executed in an unsafe context.
unsafe
code blocks aren’t necessarily dangerous, however, the contents of such blocks are not verified by the Common Language Runtime.
Therefore, it is up to the programmer to ensure that no bugs are introduced through manual memory management or casting. If not done correctly, then
those bugs can lead to memory corruption vulnerabilities such as stack overflows. unsafe
code blocks should be used with caution because
of these security and stability risks.
Ask Yourself Whether
- There are any pointers or fixed buffers declared within the
unsafe
code block.
There is a risk if you answered yes to the question.
Recommended Secure Coding Practices
Unless absolutely necessary, do not use unsafe
code blocks. If unsafe
is used to increase performance, then the Span and Memory APIs may serve a similar purpose in a safe context.
If it is not possible to remove the code block, then it should be kept as short as possible. Doing so reduces risk, as there is less code that can
potentially introduce new bugs. Within the unsafe
code block, make sure that:
- All type casts are correct.
- Memory is correctly allocated and then released.
- Array accesses can never go out of bounds.
Sensitive Code Example
public unsafe int SubarraySum(int[] array, int start, int end) // Sensitive
{
var sum = 0;
// Skip array bound checks for extra performance
fixed (int* firstNumber = array)
{
for (int i = start; i < end; i++)
sum += *(firstNumber + i);
}
return sum;
}
Compliant Solution
public int SubarraySum(int[] array, int start, int end)
{
var sum = 0;
Span<int> span = array.AsSpan();
for (int i = start; i < end; i++)
sum += span[i];
return sum;
}
See