-
Sub-task
-
Resolution: Unresolved
-
Normal
-
None
-
None
-
None
-
False
-
None
-
False
-
-
Use the following guidelines when using unmanaged code:
Unmanaged code, sometimes referred to as native code, is the code that executes outside of a managed runtime system.
- Whenever possible, replace the functionality of unmanaged code with a managed equivalent.
- Use a managed wrapper function that exposes underlying unmanaged code.
- Sanity-check and scrub all data sent to / from the unmanaged code.
- Ensure the latest security updates have been applied to the unmanaged code.
- Ensure in unmanaged code, memory is securely allocated, freed and used.
There are two important reasons why unmanaged code must be avoided:
_ Contrary to applications that run within a managed environment, such as those written using Java and .NET, _unmanaged code* is not protected from serious vulnerabilities that include buffer overflows and memory corruption.
* Attackers can leverage these vulnerabilities to inject and execute arbitrary code on a target system.
_ _Unmanaged code* may execute within a different threading model than the managed code.
* In this situation, the performance of such an application will degrade and be much more susceptible to denial of service attacks.
Imported from SD Elements: https://redhat.sdelements.com/bunits/psse-secure-development/group-2-extended-functionality-offerings/amq-clients/tasks/phase/development/141-T189/
How Tos:
C# .NET unmanaged code avoidance
Description
Avoid using unmanaged code such as native libraries and the Win32 API whenever possible. Follow the guidelines below:
- Replace unmanaged code with a managed equivalent when possible. There are a growing number of .NET libraries which provide functionality previously only available with unmanaged code.
- Use a .NET function which wraps unmanaged code. Sanity-check and scrub all data sent to/from the unmanaged code. An example is provided below.
- Apply the latest security updates to external libraries.
Code
// Call the Wrapper class public partial class _Default : System.Web.UI.Page { public string UserName { get; set; }
protected void Page_Load(object sender, EventArgs e) { UnManagedCodeWrapper wrapper = new UnManagedCodeWrapper(); UserName = wrapper.getUserName(); }
// Wrap the unmanaged code public class UnManagedCodeWrapper { [DllImport("Advapi32.dll")] static extern bool GetUserName(StringBuilder buffer, ref int size);
public string getUserName() { StringBuilder name = new StringBuilder(64);
// Validate input to all external functions int nSize = name.Capacity; GetUserName(name, ref nSize);
return name.ToString();