Search code examples
c#pointersunsafe

Why unsafe code context [related to pointer operation] is a security risk in C#?


I needed to call C library function which takes pointers as argument from one C# program. In C# we need to guard the pointer operations with #unsafe keyword. Microsoft C# documents says using pointers cause stability and security issues.

In the common language runtime (CLR), unsafe code is referred to as unverifiable code. Unsafe code in C# is not necessarily dangerous; it is just code whose safety cannot be verified by the CLR. The CLR will therefore only execute unsafe code if it is in a fully trusted assembly. If you use unsafe code, it is your responsibility to ensure that your code does not introduce security risks or pointer errors.

And the docs says

Using unsafe code introduces security and stability risks.

I am new to C# language. I worked only in C language before and in UNIX environment. I understand an improper pointer have stability issues. It may crash the program/OS or may leads to unexpected results.

These are my questions:

1)I don't understand how pointer operations can lead to an security issue. The only thing I can think is invoking an function pointer which contains malicious code, but this Stack overflow link says that unsafe context is not needed for invoking a function pointer (please correct me if my understanding is wrong). Then How disabling pointer operations will increases the security?

2)We can call C functions from C# program, and those C functions may contains malicious code. Can CLR detect this security vulnerabilities?


Solution

  • One example of security risks of the misuse of pointers is use after free. One example of this issue is a recently discovered security issue within Chrome.

    I'm not really familiar with C# but I guess that the CLR doesn't "understand" C code but rather execute it directly. Therefore I think that the CLR cannot analyze/detect issues with the C code you'd like to use.